Skip to content

Commit b50bfdd

Browse files
committed
DP
股票交易两类题型 日不会做
1 parent c605489 commit b50bfdd

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package DP.其他问题如股票;
2+
3+
/**
4+
* Created by 周杰伦 on 2018/4/9.
5+
*/
6+
public class 需要冷却期的股票交易 {
7+
public int maxProfit(int[] prices) {
8+
if (prices.length < 2)return 0;
9+
if (prices.length == 2)return prices[1] - prices[0];
10+
if (prices.length == 3) {
11+
int max = prices[1] - prices[0];
12+
max = Math.max(prices[2] - prices[1], max);
13+
max = Math.max(prices[2] - prices[0], max);
14+
return max;
15+
}
16+
//buy at i price and sell at j price and cooldown at j + 1
17+
int [][]dp = new int[prices.length][prices.length];
18+
19+
dp[0][1] = prices[1] - prices[0];
20+
for (int i = 0;i < prices.length;i ++) {
21+
for (int j = i + 1;j < prices.length;j ++) {
22+
if (i >= 3) {
23+
dp[i][j] = Math.max(prices[j] - prices[i - 3],
24+
dp[i - 3][j - 3] + prices[j] - prices[i]);
25+
}else {
26+
dp[i][j] = dp[0][1];
27+
}
28+
}
29+
}
30+
for (int i = 4;i < prices.length;i ++) {
31+
dp[0][i] = Math.max(prices[i] - prices[0], dp[0][1] + dp[3][i]);
32+
}
33+
int max = 0;
34+
for (int i = 0;i < dp.length;i ++) {
35+
for (int j = i + 1;j < dp.length;j ++) {
36+
37+
}
38+
}
39+
return max;
40+
}
41+
}

0 commit comments

Comments
 (0)