leetcode—Best Time to Buy and Sell Stock IV
2016-06-29 10:59
218 查看
题目:
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.
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
分析:
该题采用动态规划的方法。
会想到:第i天进行第j次交易的最大收益为①第i-1天进行第j次交易的最大收益②第i-1天进行j-1此交易与第i天进行交易的和 中的较大值。
于是,得到方程:
其中,
然而,这种计算方法存在一些问题:第i天的交易可与之前的交易合为一次交易。这样,j的值就减小了1。
于是,重新规划:
练习代码:
提交后,一直runtime error
于是,将二维vector降维:用一维向量记录到达第i天时的temp最优解和profit最优解。
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.
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
分析:
该题采用动态规划的方法。
会想到:第i天进行第j次交易的最大收益为①第i-1天进行第j次交易的最大收益②第i-1天进行j-1此交易与第i天进行交易的和 中的较大值。
于是,得到方程:
profit[i][j] = max(profit[i – 1][j], profit[i – 1][j – 1] + diff)
其中,
diff=prices[i]-prices[i-1] 。
然而,这种计算方法存在一些问题:第i天的交易可与之前的交易合为一次交易。这样,j的值就减小了1。
于是,重新规划:
temp[i][j] = max ( profit[i-1][j-1]+max(diff,0),temp[i-1][j]+diff) profit[i][j] = max(profit[i-1][j],temp[i][j]
练习代码:
class Solution { public: int maxProfit(int k, vector<int>& prices) { int n = prices.size(); if ( n <= 1 ) return 0; if ( k <= 0 ) return 0; int diff; vector<vector<int>> profit(n+1,vector<int>(k+1,0)); vector<vector<int>> temp(n+1,vector<int>(k+1,0)); for( int i = 2; i <= n; i++ ){ diff= prices[i-1] - prices[i-2]; for(int j = 1; j <= k; j++ ) { temp[i][j] = max(profit[i-1][j-1]+max(diff,0), temp[i-1][j]+diff); profit[i][j] = max(profit[i-1][j],temp[i][j]); } } return profit [k]; } };
提交后,一直runtime error
于是,将二维vector降维:用一维向量记录到达第i天时的temp最优解和profit最优解。
class Solution { public: int maxProfit(int k, vector<int>& prices) { int n = prices.size(); if ( n <= 1 ) return 0; if ( k <= 0 ) return 0; if ( k >= n) { int res = 0; for(int i = 1; i < n; i++ ){ if(prices[i] > prices[i-1]) res += prices[i]-prices[i-1]; } return res; } int diff; vector<int> temp(k+1,0); vector<int> profit(k+1,0); for(int i = 2; i <= n; i++ ) { diff = prices[i-1] - prices[i-2]; profit[0] = 0; temp[0] = 0; for(int j = 1; j <= k; j++ ) { temp[j] = max(profit[j-1],temp[j]+diff); profit[j] = max(temp[j],profit[j]); } } return profit[k]; } };
相关文章推荐
- linux 查看日志
- MySQL常用Json函数
- ansible入门
- android系统-3G4G通信模块适配
- 收集的小工具1【win7文件删除】
- Leetcode 355. Design Twitter 实现一个Twitter系统 解题报告
- Web版Telnet工具设计与实现
- 粘连 Footer 的 5 种方法 | CSS-Tricks
- 了解流程类型,第 4 部分:左右滑动类
- 一次性检测出一个文件夹下的所有人脸
- JAVA的反射机制浅谈
- 自动布局的数学公式
- 设置listview高度包裹内容
- swift map reduce 获取下标(index)的方法
- 蘑菇街2016研发工程师在线编程题
- 服务指令
- C语言的FILE*读取文件比CFile要快的原因分析
- java反射之getGenericSuperclass方法的用处
- Spring Cloud Config 快速入门
- 走遍世界 —— 日本