xinyu04

导航

LeetCode 122 Best Time to Buy and Sell Stock II 贪心+思维

You are given an integer array prices where prices[i] is the price of a given stock on the \(i\)th day.

On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.

Find and return the maximum profit you can achieve

Solution

和上一道题不一样,我们可以 buy, sell 多次。具体来说,我们期望最大化:

\[p[j]-p[i], i\leq j \]

所以我们既希望 \(p[j]\) 很大,也希望 \(p[i]\) 很小。如何解决?本质上序列就是一段下降一段上升再一段下降......如此反复的,对于一个上升区间,我们可以得到包含该区间的最大 \(profit\),接着同样的,我们可以得到下一个上升区间的最大 \(profit\)

看上去我们应该在得到最小值的时候,寻找下一个最近的最大值并立刻卖出。为什么不选择在下下一个最大值时候卖出呢?因为相邻区间的 \(profit\)\(range\) 至少会有重叠的,所以我们只需要贪心地选择每一个区间的 \(profit\)

点击查看代码
class Solution {
private:
    int ans=0;
    int p_buy,p_sell;
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        int i=0;
        while(i+1<n){
            while(i+1<n && prices[i]>=prices[i+1])i++;
            p_buy = prices[i];
            
            while(i+1<n && prices[i]<prices[i+1])i++;
            p_sell = prices[i];
            
            ans+=(p_sell-p_buy);
        }
        return ans;
    }
};

posted on 2022-07-20 05:16  Blackzxy  阅读(16)  评论(0编辑  收藏  举报