Best Time to Buy and Sell Stock IV
来源:互联网 发布:阿房宫读音知乎 编辑:程序博客网 时间:2024/06/05 19:47
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.
解题思路
采用动态规划来解决问题。
我们需要维护如下两个量: global[i][j]
:当前到达第i
天最多可以进行j
次交易,所得到的最大利润。 local[i][j]
:当前到达第i
天最多可以进行j
次交易,而且最后一次交易在当天卖出,所得到的最大利润。
状态转移方程: global[i][j] = max(local[i][j], global[i-1][j])
上述方程比较两个量的大小:①当前局部最大值;②过往全局最大值。 local[i][j] = max(global[i-1][j-1] + max(diff, 0), local[i-1][j] + diff)
上述方程比较两个量的大小:
①全局到i-1
天进行j-1
次交易,然后加上今天的交易(如果今天的交易赚钱的话)。
②取局部第i-1
天进行j
次交易,然后加上今天的差值(local[i-1][j]
是第i-1
天卖出的交易,它加上diff
后变成第i
天卖出,并不会增加交易次数。无论diff
是正还是负都要加上,否则就不满足local[i][j]
必须在最后一天卖出的条件了)
另外需要注意的一个问题是,当k远大于数组的大小时,上述算法将变得低效。因此将其改用不限交易次数的方式解决。
public class Solution {public int maxProfit(int k, int[] prices) {
int len = prices.length;
if (len == 0)
{
return 0;
}
if (k >= len)
{
return helper(prices);
}
int[] max_local = new int[k+1];
int[] max_global = new int[k+1];
int diff = 0;
for (int i = 0; i < len - 1; i++)
{
diff = prices[i + 1] - prices[i];
for (int j = k; j >= 1; j--)
{
max_local[j] = Math.max(max_global[j - 1] + Math.max(diff, 0), max_local[j] + diff);
max_global[j] = Math.max(max_local[j], max_global[j]);
}
}
return max_global[k];
}
int helper(int[] prices)
{
int profit = 0;
for (int i = 0; i < prices.length - 1; i++)
{
profit = Math.max(profit, profit + prices[i + 1] - prices[i]);
}
return profit;
}
}
0 0
- Best Time to Buy and Sell Stock IV
- [LeetCode] Best Time to Buy and Sell Stock IV
- Best Time to Buy and Sell Stock IV
- Best Time to Buy and Sell Stock IV
- Best Time to Buy and Sell Stock IV
- leetcode: Best Time to Buy and Sell Stock IV
- LeetCode(188) Best Time to Buy and Sell Stock IV
- Best Time to Buy and Sell Stock IV
- Best Time to Buy and Sell Stock IV -- leetcode
- Best Time to Buy and Sell Stock IV(未完成)
- Best Time to Buy and Sell Stock IV
- 【动态规划】Best Time to Buy and Sell Stock IV
- Best Time to Buy and Sell Stock IV
- Best Time to Buy and Sell Stock IV--LeetCode
- LeetCode : Best Time to Buy and Sell Stock III & IV
- Best Time to Buy and Sell Stock IV Leetcode Java
- Best Time to Buy and Sell Stock IV
- LeetCode: Best Time to Buy and Sell Stock IV
- C++引用报错:invalid initialization of non-const reference of type ‘std::string&’ from an rvalue of type
- leetcode_112_Path Sum
- HDU 5074 Hatsune Miku 暴力dp
- hadoop 中map、reduce数量对mapreduce执行速度的影响
- beaglebone ssh链接
- Best Time to Buy and Sell Stock IV
- ios中打电话功能实现的几种方式
- 浅谈高效学习的方法:打破遗忘的诅咒
- java 常用类 事例
- sencha touch + cordova使用tel:****打电话不起效的问题
- 写批处理命令bat读图片路径
- C++一些常用用法
- 修改的C++版Opengl艺术画实现
- 通过keil给stm32板下载程序出现cannot load flash programming algorithm