LeetCode:买卖股票的最佳时机 IV

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

买卖股票的最佳时机 III题解         https://blog.csdn.net/smile__dream/article/details/81700476

 

给定一个数组,它的第 i 个元素是一支给定的股票在第 天的价格。

设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。

注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

示例 1:

输入: [2,4,1], k = 2
输出: 2
解释: 在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4-2 = 2 。

示例 2:

输入: [3,2,6,5,0,3], k = 2
输出: 7
解释: 在第 2 天 (股票价格 = 2) 的时候买入,在第 3 天 (股票价格 = 6) 的时候卖出, 这笔交易所能获得利润 = 6-2 = 4 。
     随后,在第 5 天 (股票价格 = 0) 的时候买入,在第 6 天 (股票价格 = 3) 的时候卖出, 这笔交易所能获得利润 = 3-0 = 3 。

思路:无非四种状态 当天买入不买或者卖出不卖 ,我们得到状态转移方程 

        buy[i]=max(buy[i],sell[i-1]-prices)    //buy[i]代表第i笔买入自己还剩的钱 买入则减去当天的价格

        sell[i]=max(sell[i],buy[i]+prices[i])   //selle[i]代表第i笔卖出后自己还剩的钱 卖出即加入当天的价格

 

class Solution {  
    public int quick(int[] prices){
        int max=0;
        for(int i=0;i<prices.length-1;i++){
            if(prices[i+1]>prices[i])
            max+=(prices[i+1]-prices[i]);
        }
        return max;
    }
    
    public int maxProfit(int k, int[] prices) {
        int len=prices.length;
       
      if(len==1||len==0||prices==null||k==0){
          return 0;
      }
      if(k>=len/2){
        return quick(prices);
      }  
        int []buy=new int[k+1];
        int []sell=new int[k+1];
        for(int i=0;i<=k;i++){
            buy[i]=Integer.MIN_VALUE;
        }
        for(int i=0;i<len;i++){   
            for (int j = 0; j<k; j++) {
                buy[j+1] = Math.max(buy[j+1], sell[j] - prices[i]);
                sell[j+1] = Math.max(buy[j+1] + prices[i], sell[j+1]);
            }
            
        }
        return sell[k];
        
    }
}

 

Discuss:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/54113/A-Concise-DP-Solution-in-Java?page=2

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值