LeetCode-309.Best Time to Buy and Sell Stock with Cooldown

本文介绍了一种基于动态规划的算法,用于解决在特定限制条件下(如冷却期)如何通过多次买卖股票来实现最大利润的问题。提供了两种实现方式,一种是时间复杂度为O(n),空间复杂度也为O(n)的方法;另一种则是进一步优化了空间复杂度至O(1)的解决方案。

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) with the following restrictions:

  • You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
  • After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)

Example:

Input: [1,2,3,0,2]
Output: 3 
Explanation: transactions = [buy, sell, cooldown, buy, sell]

使用动态规划,时间复杂度为O(n),空间复杂度为O(n)
 1 public int maxProfit(int[] prices) {//dp mytip
 2         if(null==prices||0==prices.length){
 3             return 0;
 4         }
 5         int[][] states = new int[prices.length+1][2];//0表示此刻无股票,1表示此刻有股票,数组长度为prices.length+1是放置i-2溢出
 6         states[1][1]= -prices[0];//第一天买股票
 7         for(int i=2;i<=prices.length;i++){
 8             states[i][0]=Math.max(states[i-1][0],states[i-1][1]+prices[i-1]);//第i天无股票是第i-1天无股票和第i天卖股票的最大值
 9             states[i][1]=Math.max(states[i-2][0]-prices[i-1],states[i-1][1]);//第i天有股票是第i-1天有股票和第i天买股票的最大值
10         }
11         return states[prices.length][0];
12         
13     }

 

优化空间复杂度为O(1)

 1 public int maxProfit(int[] prices) {//dp mytip
 2         if(null==prices||0==prices.length){
 3             return 0;
 4         }
 5         int preStock = 0;//只需要保持前两天的结果,将数组优化为变量,相当于states[i-2][1]
 6         int stock =-prices[0];//states[i-1][1]
 7         int preNoStock =0;//states[i-2][0]
 8         int noStock =0;//states[i-1][0]
 9         int[][] states = new int[prices.length+1][2];
10         
11         for(int i=1;i<prices.length;i++){
12             preStock =stock;
13             stock =Math.max(preNoStock-prices[i],stock);
14             preNoStock = noStock;
15             noStock = Math.max(preStock+prices[i],noStock);
16         }
17         return noStock;
18         
19     }

 

相关题

买卖股票的最佳时间1 LeetCode121 https://www.cnblogs.com/zhacai/p/10429264.html

买卖股票的最佳时间2 LeetCode122 https://www.cnblogs.com/zhacai/p/10596627.html

买卖股票的最佳时间3 LeetCode123 https://www.cnblogs.com/zhacai/p/10645571.html

买卖股票的最佳时间4 LeetCode188 https://www.cnblogs.com/zhacai/p/10645522.html

买卖股票的最佳时间交易费 LeetCode714 https://www.cnblogs.com/zhacai/p/10659288.html


转载于:https://www.cnblogs.com/zhacai/p/10655970.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值