【LeetCode笔记】121. 买卖股票的最佳时机 / 剑指 Offer 63. 股票的最大利润(Java、动态规划)

题目描述

  • 讲道理,一眼dp
    在这里插入图片描述

代码 & 思路

  • 时间复杂度O(n),不过可改进的地方还多,跑出来大概6ms。

初版代码

class Solution {
    public int maxProfit(int[] prices) {
        // 做啥:找一个i,j(j > i)且prices[j] > prices[i],使得 max = prices[j] - prices[i]
        // 用dp做吧
        int len = prices.length;
        if(len == 1){
            return 0;
        }
        
        // dp[i]代表当前值之后能遇到的最大值
        int[] dp = new int[len];
        dp[len-1] = 0;
        for(int i=len-2;i >= 0;i--){
            dp[i] = Math.max(prices[i+1],dp[i+1]);
        }
        int max = 0;
        for(int i=0;i<len-1;i++){
            max = Math.max(dp[i] - prices[i],max);
        }
        return max;
    }
}

更新啦~优化代码

  • 节约了空间,空间复杂度由 O(n) 变成了 O(1)
class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length < 2) {
            return 0;
        }
        int len = prices.length;
        int max = prices[len - 1];
        int ans = 0;

        for(int i = len - 2; i >= 0; i--) {
            int nowProfit = max - prices[i];
            // ans 更新
            if(nowProfit > ans) {
                ans = nowProfit;
            }
            // min 更新
            if(prices[i] > max) {
                max = prices[i];
            } 
        }
        
        return ans;
    }
}

再次更新

class Solution {
    public int maxProfit(int[] prices) {
        int max = prices[prices.length - 1];
        int res = 0;
        for(int i = prices.length - 2; i >= 0; i--) {
            max = Math.max(max, prices[i + 1]);
            res = Math.max(max - prices[i], res);
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值