# leetcode中的股票问题（4）

## 原题

Say you have an array for which the ith$i^{th}$ element is the price of a given stock on day i$i$.
Design an algorithm to find the maximum profit. You may complete at most k transactions.

## 问题分析

profit(i,j)=Max(profit(i1,j),profitAt(i,j))$profit(i,j) = Max(profit(i - 1,j),profitAt(i,j))$

profitAt(i,j)$profitAt(i,j)$呢？怎么递推呢？

## 代码

public int maxProfit(int k, int[] prices) {
if(prices==null || prices.length==0)
return 0;
//如果k>一半天数，问题退化成问题（3）了
if(k > prices.length/2)
{
int sum =0;
for(int i = 0 ; i < prices.length-1 ; i++)
{
int gain = prices[i+1] - prices[i];
if(gain > 0)
sum += gain;
}
return sum;
}

int[][] global=new int[prices.length][k+1];
int[][] local=new int[prices.length][k+1];
for(int i=0;i<prices.length-1;i++)
{
int diff=prices[i+1]-prices[i];
for(int j=0;j<=k-1;j++)
{
local[i+1][j+1]=Math.max(global[i][j]+Math.max(diff,0),local[i][j+1]+diff);
global[i+1][j+1]=Math.max(global[i][j+1],local[i+1][j+1]);
}
}
return global[prices.length-1][k];
}

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

## Leetcode Best Time to Buy and Sell Stock IV

Leetcode Best Time to Buy and Sell Stock IV，本题主要是找出最大值与买卖次数的关系，很快可以求得结果。卖买次数与k的关系分析 首先我们知道当次数不限时，只需要...

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

## 121.122.123.188. Best Time to Buy and Sell Stock I II III IV

Say you have an array for which the ith element is the price of a given stock on day i. If you were...

## <LeetCode OJ> 123. / 188. Best Time to Buy and Sell Stock （III / IV）

123. Best Time to Buy and Sell Stock III My Submissions Question Total Accepted: 49478 Total Sub...

## LeetCode--Best Time to Buy and Sell Stock IV（DP + 滚动数组）

举报原因： 您举报文章：深度学习：神经网络中的前向传播和反向传播算法推导 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)