[leetcode] Best Time to Buy and Sell Stock IV
2015-03-15 10:57
405 查看
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).
题解:
参考/article/4901626.html 和 /article/1378264.html
class Solution { public: int solvemaxProfit(vector<int> prices) { int profit = 0; for(int i=0;i<prices.size()-1;i++) { if(prices[i+1]>prices[i]) profit += prices[i+1]-prices[i]; } return profit; } int maxProfit(int k, vector<int> &prices) { int n = prices.size(); if(n<=0) return 0; if(k>=n) return solvemaxProfit(prices); int global[k+1] = {0}; int local [k+1] = {0}; for(int i=0;i<n-1;i++) { int tmp = prices[i+1]-prices[i]; for(int j=k;j>=1;j--) { local[j] = max(global[j-1]+max(tmp, 0), local[j]+tmp); global[j] = max(local[j], global[j]); } } return global[k]; } };
View Code
相关文章推荐
- LeetCode(188) Best Time to Buy and Sell Stock IV
- leetcode 第188题,我的解法,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--LeetCode
- LeetCode - Best Time to Buy and Sell Stock IV
- LeetCode-Best Time to Buy and Sell Stock IV -解题报告
- LeetCode OJ Best Time to Buy and Sell Stock I II III IV
- LeetCode(188) Best Time to Buy and Sell Stock IV (Java)
- LeetCode之“动态规划”:Best Time to Buy and Sell Stock I && II && III && IV
- [LeetCode] Best Time to Buy and Sell Stock IV 买卖股票的最佳时间之四
- Leetcode: Best Time to Buy and Sell Stock IV
- [LeetCode] Best Time to Buy and Sell Stock IV
- LeetCode Best Time to Buy and Sell Stock IV
- LeetCode188:Best Time to Buy and Sell Stock IV
- LeetCode – Refresh – Best Time to Buy and Sell Stock iv
- 188. Best Time to Buy and Sell Stock IV Leetcode Python
- Best Time to Buy and Sell Stock IV -- leetcode
- 【LeetCode】 Best Time to Buy and Sell Stock I II III IV 解题报告
- Java for LeetCode 188 Best Time to Buy and Sell Stock IV【HARD】
- LeetCode : Best Time to Buy and Sell Stock III & IV