十七
十七
Published on 2022-03-13 / 151 Visits
0
0

leetcode122. 买卖股票的最佳时机 II

leetcode122. 买卖股票的最佳时机 II

单调栈

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        vector<int>sk(prices.size(),0);
        int top=-1,ans=0,hh=0;
        for(auto t:prices){
            while(top!=-1&&sk[top]>t)top--;
            if(top!=-1){
                ans+=t-sk[0];
                sk.clear();//清空
                top=-1;
            }
            sk[++top]=t;
        }
        
    return ans;
    }
};

贪心

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int ans=0;
        for(int i=1;i<prices.size();i++){
            if(prices[i]>prices[i-1])ans+=prices[i]-prices[i-1];
        }
        return ans;
    }
};

Comment