/
Solution.java
executable file
·87 lines (64 loc) · 2.22 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
public class Solution {
public int maxProfit(int k, int[] prices) {
if(k >= prices.length/2){
int res = 0;
for(int i = 1; i < prices.length; i++){
if(prices[i] > prices[i-1])
res += prices[i] - prices[i-1];
}
return res;
}
int[] local = new int[k+1], global = new int[k+1];
for(int i = 1; i < prices.length; i++){
int diff = prices[i] - prices[i-1];
for(int j = k; j > 0; j--){
local[j] = Math.max(local[j]+diff, global[j-1]+Math.max(diff, 0));
global[j] = Math.max(local[j], global[j]);
}
}
return global[k];
}
}
public class Solution {
public int maxProfit(int k, int[] prices) {
k = Math.min(k, prices.length);
if(k <= 0) return 0;
// shit cheat
if(k >= prices.length) return maxProfit(prices);
int[][] P = new int[k + 1][prices.length];
int[][] H = new int[k + 1][prices.length];
int[] D = new int[prices.length];
for(int i = 1; i < prices.length; i++){
D[i] = prices[i] - prices[i - 1];
}
int si = 1;
for(int j = 1; j <= k; j++) {
for (int i = si; i < prices.length; i++) {
H[j][i] = Math.max(H[j][i - 1] + D[i], P[j - 1][i - 1]);
P[j][i] = Math.max(H[j][i], P[j][i - 1]);
}
for (int i = si + 1; i < prices.length; i++) {
if(P[j - 1][i] == P[j][i]) {
si = i;
}
}
if(si == prices.length - 1){
return P[j][prices.length - 1];
}
}
return P[k][prices.length - 1];
}
// best-time-to-buy-and-sell-stock-ii
int maxProfit(int[] prices) {
if(prices.length <= 1) return 0;
int profit = 0;
int hold = prices[0];
for(int i = 1; i < prices.length; i++){
if(hold < prices[i]){
profit += prices[i] - hold; // sell
}
hold = prices[i];
}
return profit;
}
}