-
Notifications
You must be signed in to change notification settings - Fork 0
/
Best Time to Buy and Sell Stock IV.java
48 lines (41 loc) · 1.5 KB
/
Best Time to Buy and Sell Stock IV.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
/*
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/
Example: None
Solution: None
Source: None
*/
public class Solution {
public int maxProfit(int k, int[] prices) {
if (k == 0) {
return 0;
}
if (k >= prices.length / 2) {
int profit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
profit += prices[i] - prices[i - 1];
}
}
return profit;
}
int n = prices.length;
int[][] mustsell = new int[n + 1][n + 1];
int[][] globalbest = new int[n + 1][n + 1];
mustsell[0][0] = globalbest[0][0] = 0;
for (int i = 1; i <= k; i++) {
mustsell[0][i] = globalbest[0][i] = 0;
}
for (int i = 1; i < n; i++) {
int gainorlose = prices[i] - prices[i - 1];
mustsell[i][0] = 0;
for (int j = 1; j <= k; j++) {
mustsell[i][j] = Math.max(globalbest[(i - 1)][j - 1] + gainorlose,
mustsell[(i - 1)][j] + gainorlose);
globalbest[i][j] = Math.max(globalbest[(i - 1)][j], mustsell[i ][j]);
}
}
return globalbest[(n - 1)][k];
}
}