LeetCode 122 -- Best Time to Buy and Sell Stock II

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

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

 

Subscribe to see which companies asked this question

 解法1. 贪心算法:从前到后,遍历整个数组,如果S[i+1]大于S[i],则将二则只差添加到结果中。理解到了,代码相对简单,不再写出来。
 
 解法2 动态规划:股票必须先买后卖。对于某一天,股票手上的股票只有两种状态,sell和buy;因为最终手里面没有股票,最终需要的结果是sell.既手里股票卖了获得最大利润。所以我们可以用两个dp数组分别记录当前持有股票和未持有股票的状态。从而理清二者的转换条件。
 
       对于当天最终未持有股票。最终最大利润有两种可能,一是今天没做任何操作,跟昨天未持有股票状态一样。第二是昨天此股了,今天卖了。最大利润取二者之间的最大值即可。表达式如下 : selldp[i]  = Math.max(selldp[i-1], buydp[i-1]+prices[i]);
       对于当天持有股票,最大利润也是有两种, 一是今天跟昨天一样,持有股票。二是昨天未持有股票, 今天买入了股票。最大利润取二者最大值即可。表达式如下:buydp[i]=Math.max(buydp[i], selldp[i-1]-prices[i])
      最终结果为selldp[n-1] : 表示为最后一天结束时候手里没有股票积累的最大利润。
代码如下:
<span style="font-size:14px;">public class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length == 0){
            return 0;
        }
        int[] buydp = new int[prices.length];
        int[] selldp = new int[prices.length];
        
        buydp[0] = -prices[0];
        selldp[0] = 0;
        for(int i = 1; i < prices.length; i++){
            selldp[i] = Math.max(selldp[i-1], buydp[i-1] + prices[i]);
            buydp[i] = Math.max(buydp[i-1], selldp[i-1] - prices[i]);
        }
        return selldp[prices.length - 1];
    }
}</span>
 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值