解题思路:观察样例发现只要第二天收益为正就可以卖出。然后再重新考虑当天购买的情况
class Solution {
public:
int maxProfit(vector<int>& prices) {
int cnt = 0, flag = 1, ans = 0;
for(int i = 0; i < prices.size(); ++i){
flag *= -1;//用flag表示买卖
cnt += prices[i] * flag;
if(flag == 1){//如果是当天卖出
if(cnt > 0){//收益为正则纳入
ans += cnt;
}
i -= 1;
flag = 1;
cnt = 0;//重置
}
}
return ans;
}
};
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;
}
};
//优化的解法
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/solution/mai-mai-gu-piao-de-zui-jia-shi-ji-ii-by-leetcode-s/