-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path188. Best Time to Buy and Sell Stock IV
52 lines (50 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
//O(nk) time and space
class Solution {
public int maxProfit(int k, int[] prices) {
int n = prices.length;
if(k>=n/2) return maxProfit2(prices);
int[][] dp = new int[k+1][n];
for(int i=1;i<=k;i++){
int max = -prices[0];
for(int j=1;j<n;j++){
dp[i][j] = Math.max(dp[i][j-1], prices[j]+max);
max = Math.max(max, dp[i-1][j-1]-prices[j]);
}
}
return dp[k][n-1];
}
public int maxProfit2(int[] nums) {
if(nums==null || nums.length==0) return 0;
int max = 0;
for(int i=1;i<nums.length;i++){
if(nums[i]-nums[i-1]>0) max+=(nums[i]-nums[i-1]);
}
return max;
}
}
//O(n2k) time and O(nk)space
class Solution {
public int maxProfit(int k, int[] prices) {
int n = prices.length;
if(k>=n/2) return maxProfit2(prices);
int[][] dp = new int[k+1][n];
for(int i=1;i<=k;i++){
for(int j=1;j<n;j++){
int max = Integer.MIN_VALUE;
for(int m=0;m<j;m++){
max = Math.max(max, prices[j]-prices[m]+dp[i-1][m]);
}
dp[i][j] = Math.max(max,dp[i][j-1]);
}
}
return dp[k][n-1];
}
public int maxProfit2(int[] nums) {
if(nums==null || nums.length==0) return 0;
int max = 0;
for(int i=1;i<nums.length;i++){
if(nums[i]-nums[i-1]>0) max+=(nums[i]-nums[i-1]);
}
return max;
}
}