Best Time to Buy and Sell Stock II
unlocked question, 所以不贴截图了
This solution is really smart. 当后一个比前一个大的时候,把差值加入result中。 e.g.: {7, 1, 2, 5, 4, 3},7, 1递减,不对result操作。 1,2,5递增,5 - 1 = (2 - 1) + (5 - 2), 把(2 - 1) and (5 - 2)分别加入result。
class Solution {
public:
int maxProfit(vector<int>& prices) {
int res = 0;
for (int i = 1; i < prices.size(); i++)
res += max(prices[i] - prices[i - 1], 0);
return res;
}
};