[LeetCode] Best Time to Buy and Sell Stock IV

0
0
0
1. 云栖社区>
2. 博客>
3. 正文

## [LeetCode] 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).

### 解题思路

global[i][j]:当前到达第i天最多可以进行j次交易，所得到的最大利润。
local[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]必须在最后一天卖出的条件了）

### 实现代码

/*****************************************************************
*  @Author   : 楚兴
*  @Date     : 2015/2/22 23:42
*  @Status   : Accepted
*  @Runtime  : 15 ms
******************************************************************/
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Solution {
public:
int maxProfit(int k, vector<int> &prices) {
int len = prices.size();
if (len == 0)
{
return 0;
}
if (k >= len)
{
return helper(prices);
}

vector<int> max_local(k + 1, 0);
vector<int> max_global(k + 1, 0);
int diff;
for (int i = 0; i < len - 1; i++)
{
diff = prices[i + 1] - prices[i];
for (int j = k; j >= 1; j--)
{
max_local[j] = max(max_global[j - 1] + max(diff, 0), max_local[j] + diff);
max_global[j] = max(max_local[j], max_global[j]);
}
}

return max_global[k];
}

int helper(vector<int> &prices)
{
int profit = 0;
for (int i = 0; i < prices.size() - 1; i++)
{
profit = max(profit, profit + prices[i + 1] - prices[i]);
}

return profit;
}
};

+ 关注

corcosa 14246人浏览