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; Note the corner case.
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;}
Best solution, feel good slag.
As long as there is an increase can be added to the sum inside ... There is no need to calculate the rising range.
Still have to analyze the problem carefully.
[Leetcode] best time to Buy and Sell Stock II