# Hard-题目38：188. 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.

local[i][j] = max(global[i - 1][j - 1] + max(diff, 0), local[i - 1][j] + diff)

global[i][j] = max(local[i][j], global[i - 1][j])

class Solution {
public:
int maxProfit(int k, vector<int> &prices) {
if (prices.empty()) return 0;
//  if (k >= prices.size()) return solveMaxProfit(prices);
int g[k + 1] = {0};
int l[k + 1] = {0};
for (int i = 0; i < prices.size() - 1; ++i) {
int diff = prices[i + 1] - prices[i];
for (int j = k; j >= 1; --j) {
l[j] = max(g[j - 1] + max(diff, 0), l[j] + diff);
g[j] = max(g[j], l[j]);
}
}
return g[k];
}
int solveMaxProfit(vector<int> &prices) {
int res = 0;
for (int i = 1; i < prices.size(); ++i) {
if (prices[i] - prices[i - 1] > 0) {
res += prices[i] - prices[i - 1];
}
}
return res;
}
};

8ms,63.62%,12ms,41.65%

• 本文已收录于以下专栏：

## [LeetCode] Best Time to Buy and Sell Stock IV

Say you have an array for which the ithi^{th} element is the price of a given stock on day ii.Design...
• u011331383
• 2015年02月23日 00:08
• 8758

## LeetCode(188) Best Time to Buy and Sell Stock IV (Java)

• feliciafay
• 2015年04月19日 15:45
• 5472

## LeetCode(188) Best Time to Buy and Sell Stock IV

• feliciafay
• 2015年03月23日 08:37
• 1952

## 【LeetCode】Best Time to Buy and Sell Stock IV 动态规划dp解法（C++）

• u011613729
• 2015年08月14日 14:14
• 1254

## 【LeetCode】 Best Time to Buy and Sell Stock I II III IV 解题报告

Best Time to Buy and Sell Stock I题意：用一个数组表示股票每天的价格，数组的第i个数表示股票在第i天的价格。 如果只允许进行一次交易，也就是说只允许买一支股票并卖掉，求...
• ljiabin
• 2015年04月06日 11:10
• 21729

## 关于LeetCode中Best Time to Buy and Sell Stock一题的理解

• zsy112371
• 2016年09月09日 13:55
• 831

## Leetcode 188 Best Time to Buy and Sell Stock IV 至多k次买卖股票最大收益

• smile_watermelon
• 2015年08月12日 15:50
• 918

## Best Time to Buy and Sell Stock III -- LeetCode

• linhuanmars
• 2014年04月09日 05:34
• 27241

## [leetcode 309]Best Time to Buy and Sell Stock with Cooldown--买卖股票with冷却期（DP法）

Question: Say you have an array for which the ith element is the price of a given stock on day ...
• Xiaohei00000
• 2016年03月10日 23:02
• 1747

## 【LeetCode】【Python题解】Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i. Design an...
• u011613729
• 2014年07月24日 10:11
• 3434

举报原因： 您举报文章：Hard-题目38：188. Best Time to Buy and Sell Stock IV 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)