188. Best Time to Buy and Sell Stock IV
2016-06-28 09:25
281 查看
Problem
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)
Solution
采用动态规划来解决问题。我们需要维护如下两个量:
local[i][j]:当前到达第i天最多可以进行j次交易 ,而且最后一次交易在第i天卖出,所得到的最大利润。
global[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远大于数组的大小时,上述算法将变得低效。因此将其改用不限交易次数的方式解决。
class Solution { public: int maxProfit(int k, vector<int>& prices) { int n = prices.size(); if(n<2) return 0; if(k >=n) return maxProfit2(prices); vector<vector<int>> local(n,vector<int>(k+1,0)); vector<vector<int>> global(n,vector<int>(k+1,0)); for(int i = 1;i<n;++i) { int diff = prices[i] - prices[i-1]; for(int j = 1;j<=k;++j) { local[i][j] = max(global[i - 1][j - 1], local[i - 1][j] + diff); global[i][j] = max(global[i - 1][j], local[i][j]); } } return global[n-1][k]; } private: int maxProfit2(vector<int>& prices) { int maxProfit = 0; int n = prices.size(); for(int i = 1;i<n;++i) { int diff = prices[i] - prices[i-1]; if(diff > 0) maxProfit+=diff; } return maxProfit; } };
相关文章推荐
- UVa 10935 queue教学
- jQuery 调用WebService 实例讲解
- 找出丢失的数字
- 基于二进制的权限管理与验证
- Linux下su与su -命令的本质区别
- 关于Studio和EclipseSHA1值的查看
- GIT常用命令整理
- 关于XML和JSON
- JAVA 对象拷贝
- bzoj1803: Spoj1487 Query on a tree III
- [bzoj2938] [Poi2000]病毒
- Container With Most Water Leetcode Python Java
- [LC338] Counting Bits
- git学习
- jsp登录会话的简单实现
- @SessionAttributes和@ModelAttribute
- java多线程-用多线程找出最大随机数
- 《C#类设计手册》基础知识要点
- DNS原理入门
- cpu组相连映射