121 Best Time to Buy and Sell Stock

本文探讨了如何使用动态规划解决买卖股票以获取最大利润的问题。通过两种不同的解题思路,详细阐述了从数组中寻找最大利润的方法,并对比了各自的效率。最后提供了代码实现,展示了时间复杂度为O(n)的高效解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

题目:

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

解题思路:
这题一看就是动态规划。
最基础的想法是,对于数组中的每一个元素,在下标大于它的元素中找到最大的一个元素,它们的差值就是该元素的最大利润。
这种想法的时间复杂度很高,对每一个元素都要求它之后的最大值。

换个角度思考,可以从数组尾部开始遍历元素,同样是找到最大值,进行比较,但是每向前推进一个元素,最大值的更新过程变得很简单,是老的最大值和刚遍历过的元素两者取最大值。再和当前元素求差值,得到当前元素的最大利润。

补充一下大神的解法,也很巧妙:
很容易感觉出来这是动态规划的题目,用“局部最优和全局最优解法”。
1. 思路是维护两个变量,一个是到目前为止最好的交易,另一个是在当前一天卖出的最佳交易(也就是局部最优)。
2. 递推式是:
local[i+1]=max(local[i]+prices[i+1]-price[i],0)
global[i+1]=max(local[i+1],global[i])。
3. 这样一次扫描就可以得到结果,时间复杂度是O(n)。而空间只需要两个变量,即O(1)。

代码实现:
自己的思路:

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length == 0)
            return 0;
        int max = prices[prices.length - 1];
        int maxProfit = -1;
        for(int i = prices.length - 2; i >= 0; i --) {
            int localProfit = max - prices[i];
            if(maxProfit < localProfit)
                maxProfit = localProfit;
            if(max < prices[i])
                max = prices[i];
        }
        return maxProfit < 0 ? 0 : maxProfit;
    }
}
198 / 198 test cases passed.
Status: Accepted
Runtime: 2 ms

大神的思路:

public class Solution {
    public int maxProfit(int[] prices) {  
        if(prices==null || prices.length==0)  
            return 0;  
        int local = 0;  
        int global = 0;  
        for(int i=0;i<prices.length-1;i++)  
        {  
            local = Math.max(local+prices[i+1]-prices[i],0);  
            global = Math.max(local, global);  
        }  
        return global;  
    }  
}
198 / 198 test cases passed.
Status: Accepted
Runtime: 3 ms
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值