best time to Buy and Sell Stock

Source: Internet
Author: User

Given a vector, the vector represents the price of a stock in the first day, Y to make the stock yield the largest should be bought on the day I, the first i+n days to sell, to find out the value of the maximum profit is how much

Idea: Record the minimum value with a variable, a variable record the maximum benefit, scan the price from beginning to end, when scanning to the price of the day I, if the price is smaller than the minimum value, then replace, if it is larger than the minimum value, then calculate whether the profit of the moment is greater than the maximum benefit, or the replacement, or continue.

  
 
  1. class Solution {
  2. public:
  3. int maxProfit(vector<int> &prices) {
  4. int profit = 0;
  5. int minIndex = 0;
  6. for (size_t i = 1; i < prices.size(); i++)
  7. {
  8. if (prices[i] < prices[minIndex])
  9. {
  10. minIndex = i;
  11. }
  12. else if (prices[i] - prices[minIndex] > profit)
  13. {
  14. profit = prices[i] - prices[minIndex];
  15. }
  16. }
  17. return profit;
  18. }
  19. };


From for notes (Wiz)

best time to Buy and Sell Stock

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.