122. Best Time to Buy and Sell Stock II
- Total Accepted: 96307
- Total Submissions: 221716
- Difficulty: Medium
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).
思路:相邻天的差价组成新的序列S={0,prices[1]-prices[0],prices[2]-prices[1]...prices[n-1]-prices[n-2]}。那么问题就可以转换为求序列S中多个连续子序列和的最大值,其实就是将S中所有大于0的元素相加。
代码:
1 class Solution { 2 public: 3 int maxProfit(vector<int>& prices) { 4 if(prices.size()<2) return 0; 5 int i,sum=0,cursum=0,n=prices.size(); 6 for(i=1;i<n;i++){ 7 int temp=prices[i]-prices[i-1]; 8 if(temp>0){ 9 sum+=temp; 10 } 11 } 12 return sum; 13 } 14 };