Skip to content

Commit a432ddb

Browse files
authored
Create 188. Best Time to Buy and Sell Stock IV
1 parent 57b7376 commit a432ddb

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
class Solution {
2+
public int maxProfit(int k, int[] prices) {
3+
4+
int n = prices.length;
5+
int[][] dp = new int[k+1][n];
6+
7+
if(n < 2) return 0;
8+
9+
for(int i = 1; i <= k; i++) {
10+
for(int j = 1; j < n; j++) {
11+
dp[i][j] = Math.max(dp[i][j-1], helper(i, j, prices, dp));
12+
}
13+
}
14+
15+
return dp[k][n-1];
16+
17+
}
18+
19+
private int helper(int k, int x, int[] prices, int[][] dp){
20+
int max = 0;
21+
for(int i = 0; i < x; i++) {
22+
//Sell on day_x, buy on day_i and add profit from (i-1) transsactions dp[k-1][i]
23+
max = Math.max(max, prices[x]-prices[i] + dp[k-1][i]);
24+
}
25+
return max;
26+
}
27+
}
28+
29+
30+
31+
class Solution {
32+
public int maxProfit(int k, int[] prices) {
33+
34+
int n = prices.length;
35+
int[][] dp = new int[k+1][n]; //Space : O(KN)
36+
37+
if(n < 2) return 0;
38+
39+
//Time O(K*N)
40+
for(int i = 1; i <= k; i++) {
41+
int effectiveBuyPrice = prices[0];
42+
for(int j = 1; j < n; j++) {
43+
//Profit by selling on current price (j)
44+
// Profit = SP-EBP
45+
// SP => price[j]
46+
// BP => Effective Buy Price -> price[j] - previous profit (dp[k-1][j])
47+
dp[i][j] = Math.max(dp[i][j-1], prices[j] - effectiveBuyPrice);
48+
effectiveBuyPrice = Math.min(effectiveBuyPrice, prices[j] - dp[i-1][j]);
49+
}
50+
}
51+
return dp[k][n-1];
52+
}
53+
}

0 commit comments

Comments
 (0)