0%

122. Best Time to Buy and Sell Stock II

greedy O(n) time O(1) space
只要挣钱(后一天比前一天价格高)就买进卖出

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
int res = 0;
for (int i = 1; i < n; ++i) {
res += max(prices[i] - prices[i - 1], 0);
}
return res;
}
};