122. 买卖股票的最佳时机 II
方法一
贪心算法:在每一步总是做出在当前看来最好的选择
class Solution {
public:
int maxProfit(vector<int>& prices) {
int sum = 0;
for(int i = 1; i < prices.size(); i++){
if(prices[i] > prices[i-1]){
sum += (prices[i] - prices[i-1]);
}
}
return sum;
}
};
class Solution {
public:
int maxProfit(vector<int>& prices) {
int ans = 0;
int n = prices.size();
for (int i = 1; i < n; ++i) {
ans += max(0, prices[i] - prices[i - 1]);
}
return ans;
}
};