122.买卖股票的最佳时机Ⅱ

  • 122.买卖股票的最佳时机Ⅱ

  • 题目:
    一个数组prices的每个元素prices[ i ] 表示一支特定股票当天的价格;
    不能同时持有多只股票,只能卖出去才能再买;
    求最高利润;

  • 思路:
    股票系列问题是典型的DP问题;
    但本题还可以用贪心,更简单;

1.DP:O(n),O(1)
维护两个变量:持有股票的最多钱 和 不持有股票的最多钱

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res = 0;
        int n = prices.size();
        int hold_stack = (-1) * prices[0], nohold_stack = 0;
        for (int i = 1; i < n; ++i) {
            hold_stack = max(hold_stack, nohold_stack - prices[i]);
            nohold_stack = max(nohold_stack, hold_stack + prices[i]);
        }
        return nohold_stack;
    }
};

2.贪心:O(n),O(1)
这道买卖股票题是最简单的,没有手续费。因此只累计递增区间即可;

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res = 0;
        int n = prices.size();
        for (int i = 1; i < n; ++i) {
            int curDif = prices[i] - prices[i - 1]; 
            if (curDif > 0) res += curDif; 
        }
        return res;
    }
};
  • 总结:
    股票问题右很多题,目前只刷过两题,等刷完本系列再统一总结;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值