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;
}
};