LeetCode题解:121. 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.

Example 1:

Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

简单的动态规划问题:

思路1:

用一个变量minPrice记录遍历到第i天的时候,最低的价格,另外一个变量maxPro 记录到遍历到当前天的时候,最大的利润。

public class Solution {
    public int maxProfit(int[] prices) {
        int minPrice = Integer.MAX_VALUE, maxPro = 0;
        for (int price : prices) {
            minPrice = Integer.min(price, minPrice);
            maxPro = Integer.max(maxPro, price - minPrice);
        }
        return maxPro;
    }
}


思路2:

设buy[i]表示第i天 手里仍有未卖出的股票 最大利润。sell[i]表示第i天手里已经没有未卖出的股票 获得的最大利润。

状态转移方程为:

buy[i] = max{buy[i-1],-prices[i-1]} , i>=1&&i<=n 

sell[i] = max{sell[i-1],buy[i]+prices[i-1]} i>=1&&i<=n

其中buy[i]的作用相当于在前i天中选一个价格最小的,这样有可能会获得最大利润。

但是光买的时候价格最低没有用,需要两天的价格差值最大才可以。比如 价格序列为5,10,1,2 这样的话,价格最低的是1,1后面只有2了,所以得到的最大利润是1,显然是错误的。

所以需要sell来控制最大的差值,buy会更新成最小的价格,但是更新了不一定会有用,最后由sell来控制最大的差值。

但是sell和buy的更新只用到了前一天的数据,所以优化成如下:

buy = max{buy,-prices[i-1]}

sell = max{sell,buy+prices[i-1]} i>=1&&i<=n

public class Solution {
    public int maxProfit(int[] prices) {
        int buy = Integer.MIN_VALUE, sell = 0;
        for (int price : prices) {
            buy = Integer.max(buy, -price);
            sell = Integer.max(sell, buy + price);
        }
        return sell;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值