[Leetcode]Best Time to Buy and Sell Stock II
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if(n<=1) return 0;
if(n==2) return prices[1]>prices[0] ? prices[1] - prices[0] : 0;
int profit = 0;
int begin = 0;
int end = 0;
for(int i = 0;i<n-1;++i) {
while(prices[i]>=prices[i+1] ) {
i++;
if(i==n-1) return profit;
if(i== n-2) {
if(prices[i] >= prices[i+1])
return profit;
else {
profit += prices[i+1] -prices[i];
return profit;
}
}
}
begin = i;
while(i!=n-1 && prices[i]<prices[i+1]) i++;
end = i;
profit +=prices[end] - prices[begin];
}
return profit;
注意边角情况。
int maxProfit(vector<int> &prices) {
int ret = 0;
for (size_t p = 1; p < prices.size(); ++p)
ret += max(prices[p] - prices[p - 1], 0);
return ret;
}
最优解答,感觉自己好渣。
只要有增加就可以加到总和里面。。。不需要计算上涨的区间。。
还是要仔细分析问题啊。

浙公网安备 33010602011771号