easy 买卖股票的最佳时机II 贪心 队列

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述


贪心:

累和每一个上升的相邻区间


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

在这里插入图片描述


一次遍历:

假设第 i 天卖出,记录第 i 天以前的最小买入价。遇到连续上升的情况,如 prices = [1,2,3,4,5],第1天买入,第二天卖出,第2天买入,第3天卖出。。。利润与第1天买入,第5天卖出的价格一样。
即:记录每个价格上升趋势中,相邻点,低点买入,高点卖出的利润总和。


class Solution {
public:
    int maxProfit(vector<int>& prices) {
        
        int ans = 0;
        int minprice = prices[0];  // c++ 定义正无穷 1e9 = 10^9 
        int maxProfit = 0;
        
        for (auto price : prices){  // c++ 遍历 vector 元素
            minprice = min(minprice, price);
            maxProfit = max(price - minprice, maxProfit);
            if (maxProfit>0){  // 该上升区间算完,股票已卖出,重置最低价为当前买入价,重置最大利润为0
                ans += maxProfit;
                maxProfit = 0;
                minprice = price;
            }
        }

        return ans;
    }
};


队列:


class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.empty()){
            return 0;
        }

        int ans = 0;
        queue <int> p;  // 创建队列

        for (auto price : prices){
            if( !p.empty() && price <= p.back()){ // 上大下小,队底入,现在的价格下降了
                p.pop();  // 弹出队顶价格
            }
            if(!p.empty() && price > p.back()){
                ans += price - p.front();
                p.pop();  // 弹出队顶价格
            }

            p.push(price);
        }
        return ans;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值