【leetcode】Best Time to Buy and Sell Stock II

Best Time to Buy and Sell Stock II

 

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

其核心就是找到所有的单调递增区间,然后卖出去
 
最简单的,每当有涨价,就卖出去,累加所有收益(Accept了,不过似乎 buy one and sell one share of the stock multiple times了)
 
 
 1 class Solution {

 2 public:

 3     int maxProfit(vector<int> &prices) {

 4         

 5         int profit=0;

 6         for(int i=1;i<prices.size();i++)

 7         {

 8             if(prices[i]>prices[i-1])

 9             {

10                 profit+=prices[i]-prices[i-1];

11             }

12         }

13         return profit;

14         

15     }

16 };

 

 
下面代码找到了递增的区间,然后在最后一天卖出
 1 class Solution {

 2 public:

 3     int maxProfit(vector<int> &prices) {

 4        

 5        

 6         int profit=0;

 7         int n=prices.size();

 8        

 9         if(n==0)

10         {

11             return 0;

12         }

13         int buyPrice=prices[0];

14        

15         for(int i=1;i<n;i++)

16         {

17             if(prices[i]<prices[i-1])

18             {

19                 profit+=prices[i-1]-buyPrice;

20                 buyPrice=prices[i];

21             }

22         }

23        

24         profit+=prices[n-1]-buyPrice;

25        

26         return profit;

27        

28     }

29 };

 

 
 

你可能感兴趣的:(LeetCode)