Leetcode188. Best Time to Buy and Sell Stock IV

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];
	}
};






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值