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];
}
};
股票买卖最佳时机
本文介绍了一个使用动态规划解决股票买卖问题的算法。该算法通过定义两个二维数组来追踪最大利润,一个表示最后一次交易发生在某一天的利润,另一个表示在某一天的最大累积利润。通过迭代这些数组,可以找到最多进行k次交易的最大利润。
498

被折叠的 条评论
为什么被折叠?



