Say you have an array for which the i-th 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.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Example 1:
Input: [2,4,1], k = 2
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
Example 2:
Input: [3,2,6,5,0,3], k = 2
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4.
Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
说明:参考 https://blog.csdn.net/linhuanmars/article/details/23236995
class Solution {
public int maxProfit(int k, int[] prices) {
if(prices.length < 2) {
return 0;
}
if(k >= prices.length) {
return nmaxp(prices);
}
//参考:https://blog.csdn.net/xiaocong1990/article/details/80528110
int[] global = new int[k + 1];
int[] local = new int[k + 1];
for(int i = 1; i < prices.length; i++) {
int diff = prices[i] - prices[i - 1];
//因为local[j]和global[j]的计算需要依赖于i - 1次计算的local[j-1]和global[j -1],所以需要j从高到低进行遍历,这样才不会变
for(int j = k; j >0; j--) {
local[j] = Math.max(global[j - 1] + Math.max(diff, 0), local[j] + diff);
global[j] = Math.max(local[j], global[j]);
}
}
return global[k];
}
public int nmaxp(int[] prices) {
int sum = 0;
for(int i = 1; i <prices.length; i++) {
if(prices[i] > prices[i- 1]) {
sum += prices[i] - prices[i - 1];
}
}
return sum;
}
}