LeetCode121——买卖股票的最佳时机

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/

题目描述:

知识点:动态规划

思路一:双重循环

对每一天i,寻找能取得最大利润的一天j,j > i。

时间复杂度是O(n ^ 2),其中n为prices数组的大小。空间复杂度是O(1)。

JAVA代码:

public class Solution {
    public int maxProfit(int[] prices) {
        int result = 0;
        for(int i = 0; i < prices.length; i++){
            for(int j = i + 1; j < prices.length; j++){
                if(prices[j] - prices[i] > result){
                    result = prices[j] - prices[i];
                }
            }
        }
        return result;
    }
}

LeetCode解题报告:

思路二:动态规划

状态定义:f(x) -------- [0, x - 1]范围内的最低价格

状态转移:f(x + 1) = min(f(x), prices[x - 1])

时间复杂度和空间复杂度均是O(n),其中n为prices数组的大小。

JAVA代码:

public class Solution {
    public int maxProfit(int[] prices) {
        int result = 0;
        if(prices.length == 0){
            return result;
        }
        int[] dp = new int[prices.length];
        dp[0] = Integer.MAX_VALUE;
        for(int i = 1; i < dp.length; i++){
            if(prices[i - 1] < dp[i - 1]){
                dp[i] = prices[i - 1];
            }else{
                dp[i] = dp[i - 1];
            }
        }
        for(int i = 1; i < dp.length; i++){
            if(prices[i] - dp[i] > result){
                result = prices[i] - dp[i];
            }
        }
        return result;
    }
}

LeetCode解题报告:

思路三:对每个价格点,寻求最大利润

用int型变量minPrice记录前i - 1天的最低价格,我们不可能在第0天卖出,因此卖出时间i从第1天开始遍历。

对于每一天i,如果在第i天卖出,那么取得的利润就是prices[i] - minPrice,取该值和result中的较大者作为新的result值。

时间复杂度是O(n)。空间复杂度是O(1)。

JAVA代码:

public class Solution {
    public int maxProfit(int[] prices) {
        int result = 0;
        if(0 == prices.length){
            return result;
        }
        int minPrice = prices[0];
        for(int i = 1; i < prices.length; i++){
            result = Math.max(result, prices[i] - minPrice);
            minPrice = Math.min(minPrice, prices[i]);
        }
        return result;
    }
}

LeetCode解题报告:

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值