您的位置:首页 > 其它

LeetCode Best Time to Buy and Sell Stock with Cooldown

2015-12-27 13:37 501 查看
Description:

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)

Solution:

This problem is similar to Best Time To Buy and Sell Stock 2, but with a condition, that we cannot buy the stock after the first time we sell it. This condition makes the previous greedy problem to DP problem.

The transformation equation here is a very interesting.

dp[i][0] represents the maximum money you can have if you have some stock at hand on the ith day

dp[i][1] represents the maximum money you can have if you just sell the stocks on the ith day

dp[i][2] represents the maximum money you can have if you are in cooldonw condition on the ith day

so we can get

dp[i][0] = max( dp[i-1][0], dp[i-1][2] - prices[i])

dp[i][1] = dp[i-1][0] + prices[i]

dp[i][2] = max( dp[i-1][1], dp[i-1][2] )

<span style="font-size:18px;">public class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
if (n == 0)
return 0;

int dp[][] = new int
[3];
dp[0][0] = -prices[0];// have stock in hand
dp[0][1] = 0;// sell
dp[0][2] = 0;// cool down

for (int i = 1; i < n; i++) {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][2] - prices[i]);
dp[i][1] = dp[i - 1][0] + prices[i];
dp[i][2] = Math.max(dp[i - 1][1], dp[i - 1][2]);
}

int ret = Math.max(dp[n - 1][0], Math.max(dp[n - 1][1], dp[n - 1][2]));
return ret;
}
}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: