Leetcode188. Best Time to Buy and Sell Stock IV
题目:
关系如下:
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.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
题目分析:
这道题其实和第三道题是一个意思,都是用的动态规划来解决,最重要的是找到他们之间的关系。
算法分析:
定义 两个二维数组
local[i][j](i表示第几个股票,j表示销售次数)(表示最后一次交易在第i天交易的最大利润)
global[i][j] (i表示第几个股票,j表示销售次数) (表示在第i天的最大利润)
if (j == 0) {
local[i][j] = max(max(0,diff),local[i - 1][j] + diff);
global[i][j] = max(local[i][j], global[i - 1][j]);
}
else {
local[i][j] = max(global[i - 1][j - 1] + (diff > 0 ? diff : 0), local[i - 1][j] + diff);
global[i][j] = max(local[i][j], global[i - 1][j]);
}
class Solution {
public:
int maxProfit(int k, vector<int> &prices) {
if (prices.empty()) return 0;
k = k > prices.size() ? prices.size() : k;
//if (k >= prices.size()) return solveMaxProfit(prices);
//int g[k + 1] = { 0 };
//int l[k + 1] = { 0 };
int *g = new int[k + 1]();
int *l = new int[k + 1]();
for (int i = 0; i < prices.size() - 1; ++i) {
int diff = prices[i + 1] - prices[i];
for (int j = k; j >= 1; --j) {
l[j] = max(g[j - 1] + max(diff, 0), l[j] + diff);
g[j] = max(g[j], l[j]);
}
}
return g[k];
}
};