# 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];
}

04-19 5850

04-06 2.3万

08-12 1208

05-02 860

04-09 3万

09-09 1914

10-23 717

08-14 8649

05-28 1366

03-23 2106