-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path188. Best Time to Buy and Sell Stock IV
53 lines (41 loc) · 1.51 KB
/
188. Best Time to Buy and Sell Stock IV
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
class Solution {
public int maxProfit(int k, int[] prices) {
int n = prices.length;
int[][] dp = new int[k+1][n];
if(n < 2) return 0;
for(int i = 1; i <= k; i++) {
for(int j = 1; j < n; j++) {
dp[i][j] = Math.max(dp[i][j-1], helper(i, j, prices, dp));
}
}
return dp[k][n-1];
}
private int helper(int k, int x, int[] prices, int[][] dp){
int max = 0;
for(int i = 0; i < x; i++) {
//Sell on day_x, buy on day_i and add profit from (i-1) transsactions dp[k-1][i]
max = Math.max(max, prices[x]-prices[i] + dp[k-1][i]);
}
return max;
}
}
class Solution {
public int maxProfit(int k, int[] prices) {
int n = prices.length;
int[][] dp = new int[k+1][n]; //Space : O(KN)
if(n < 2) return 0;
//Time O(K*N)
for(int i = 1; i <= k; i++) {
int effectiveBuyPrice = prices[0];
for(int j = 1; j < n; j++) {
//Profit by selling on current price (j)
// Profit = SP-EBP
// SP => price[j]
// BP => Effective Buy Price -> price[j] - previous profit (dp[k-1][j])
dp[i][j] = Math.max(dp[i][j-1], prices[j] - effectiveBuyPrice);
effectiveBuyPrice = Math.min(effectiveBuyPrice, prices[j] - dp[i-1][j]);
}
}
return dp[k][n-1];
}
}