Best Time to Buy and Sell Stock IV
来源:互联网 发布:深圳网络大学报名时间 编辑:程序博客网 时间:2024/06/01 09:57
首先要想到的是利用动态规划来解DP[i][j]代表的是截止第j天,最多进行i次交易所能获得的最大利润,这样最终DP[k][n-1]便是所求答案。
值得注意的是,leetcode上对这道题的测试在k的取值上有一点trick。如果直接进行动态规划,会发现由于k过大而产生 Runtime Error 或者 MLE,关键在于要意识到如果k是大于n/2,那么意味着可以进行最优的交易过程,即每当第二天价格比第一天高,就出售,这样可以得到最优解。当然,如果k小于n/2,则不一定可以达到这个最优解了。
class Solution {public: int maxProfit(int k, vector<int> &prices) { int n=prices.size(); if(n<2) { return 0; } if(k>=n/2) { int res=0; for(int i=1;i<n;++i) { if(prices[i]>prices[i-1]) { res+=prices[i]-prices[i-1]; } } return res; } vector<vector<int> > dp(k+1,vector<int>(n,0)); for(int i=1;i<=k;++i) { int tmpMax=dp[i-1][0]-prices[0]; for(int j=1;j<n;++j) { dp[i][j]=max(dp[i][j-1],prices[j]+tmpMax); tmpMax=max(tmpMax,dp[i-1][j]-prices[j]); } } return dp[k][n-1]; }};
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
- 如何在 Windows XP SP2 中解决与 WMI 相关的问题
- HTML5游戏开发技术基础整理
- Native Client初探
- com.mysql.jdbc.Connection.isValid(I)Z Error问题
- IO流学习
- Best Time to Buy and Sell Stock IV
- LeetCode Number of 1 Bits
- 【C++11】新特性——std::function
- C++强大背后
- git 命令笔记
- 当梦想照进现实
- 【龙书笔记】编译器简介及程序构建过程综述
- 在一个线程中操作窗体线程的控件
- 拖拽的实现(com 基于windos sdk)