309. Best Time to Buy and Sell Stock with Cooldown
Posted 我的名字叫周周
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了309. Best Time to Buy and Sell Stock with Cooldown相关的知识,希望对你有一定的参考价值。
/* * 309. Best Time to Buy and Sell Stock with Cooldown * 2016-7-4 by Mingyang * http://buttercola.blogspot.com/2016/01/leetcode-best-time-to-buy-and-sell.html * *1. Define States * *To represent the decision at index i: *buy[i]: Max profit till index i. The series of transaction is ending with a buy. *sell[i]: Max profit till index i. The series of transaction is ending with a sell. *To clarify: *Till index i, the buy / sell action must happen and must be the last action. * It may not happen at index i. It may happen at i - 1, i - 2, ... 0. *In the end n - 1, return sell[n - 1]. Apparently we cannot finally end up with a buy. *In that case, we would rather take a rest at n - 1. *For special case no transaction at all, classify it as sell[i], so that in the end, we can still return sell[n - 1]. * *2. Define Recursion * *buy[i]: To make a decision whether to buy at i, we either take a rest, by just using the old decision at i - 1, *or sell at/before i - 2, then buy at i, We cannot sell at i - 1, then buy at i, because of cooldown. *sell[i]: To make a decision whether to sell at i, we either take a rest, by just using the old decision at i - 1, *or buy at/before i - 1, then sell at i. *So we get the following formula: *buy[i] = Math.max(buy[i - 1], sell[i - 2] - prices[i]); *sell[i] = Math.max(sell[i - 1], buy[i - 1] + prices[i]); */ public int maxProfit5(int[] prices) { if (prices == null || prices.length <= 1) { return 0; } int[] sell=new int[prices.length]; int[] buy=new int[prices.length]; buy[0] = -prices[0]; sell[0] = 0; buy[1]=Math.max(buy[0],-prices[1]); sell[1]=Math.max(sell[0],buy[0]+prices[1]); for (int i = 2; i <prices.length; i++) { buy[i]=Math.max(buy[i-1],sell[i-2]-prices[i]); sell[i]=Math.max(sell[i-1],buy[i-1]+prices[i]); } return sell[prices.length-1]; }
以上是关于309. Best Time to Buy and Sell Stock with Cooldown的主要内容,如果未能解决你的问题,请参考以下文章
309. Best Time to Buy and Sell Stock with Cooldown
309. Best Time to Buy and Sell Stock with Cooldown
[动态规划] leetcode 309 Best Time to Buy and Sell Stock with Cooldown
leetcode 309. Best Time to Buy and Sell Stock with Cooldown
算法: 冷却时间买卖股票的最佳时机309. Best Time to Buy and Sell Stock with Cooldown
算法: 加冷冻期时间的买卖股票309. Best Time to Buy and Sell Stock with Cooldown