LeetCode第 121 题:买股票的最佳时机(C++)

121. 买卖股票的最佳时机 - 力扣(LeetCode)
在这里插入图片描述
股票系列:
LeetCode第 121 题:买股票的最佳时机(C++)_zj-CSDN博客
LeetCode第 122 题:买股票的最佳时机II(C++)_zj-CSDN博客
LeetCode第 123 题:买股票的最佳时机III(C++)_zj-CSDN博客
LeetCode第 188 题:买股票的最佳时机IV(C++)_zj-CSDN博客
LeetCode第 309 题:最佳买卖股票时机含冷冻期(C++)_zj-CSDN博客
LeetCode第 714 题:买卖股票的最佳时机含手续费(C++)_zj-CSDN博客

暴力法

O(n^2),超时

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

动态规划

O(n^2)的dp: 最后一个测试样例超时:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        if(n == 0) return 0;
        vector<int> dp(n, 0);
        for(int i = 0; i < n; ++i){
            int val = 0;
            for(int j = 0; j < i; ++j){
                if(prices[j] < prices[i]){
                    val = max(val, prices[i] - prices[j]);
                }
            }
            dp[i] = val;
        }
        return *max_element(dp.begin(), dp.end());
    }
};

O(n)的dp:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        if(n == 0) return 0;
        vector<int> dp(n, 0);//dp[i]表示第i天卖出的最大收益,初始化为0
        int min_p = prices[0];//表示前i-1天的最小价格
        for(int i = 1; i < n; ++i){
            dp[i] = max(dp[i-1], prices[i] - min_p);
            min_p = min(min_p, prices[i]);//过了一天,更新最小价格
        }
        return *max_element(dp.begin(), dp.end());
    }
};

空间优化,状态转移过程只涉及前一个状态,所以用变量代替就可以:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.empty()) return 0;
        int min_p = prices[0], res = 0;//min_p表示第i天之前的最小价格
        for(int i = 1; i < prices.size(); ++i){//i从第一天开始
            res = max(res, prices[i] - min_p);
            min_p = min(min_p, prices[i]);//过了一天,更新最小价格
        }
        return res;
    }
};

不用dp

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.empty()) return 0;
        int min_p = prices[0], res = 0;//min_p表示第i天之前的最小价格
        for(int i = 1; i < prices.size(); ++i){//i从第一天开始
            if(prices[i] < prices[i-1]) min_p = min(min_p, prices[i]);
            else res = max(res, prices[i] - min_p);
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值