|
| 1 | +/** |
| 2 | + * Time : O() ; Space: O() |
| 3 | + * @tag : Dynamic Programming |
| 4 | + * @by : Steven Cooks |
| 5 | + * @date: Sep 30, 2015 |
| 6 | + *************************************************************************** |
| 7 | + * Description: |
| 8 | + * |
| 9 | + * Say you have an array for which the ith element is the price of a given stock on day i. |
| 10 | + * |
| 11 | + * Design an algorithm to find the maximum profit. You may complete at most k transactions. |
| 12 | + * |
| 13 | + * Note: You may not engage in multiple transactions at the same time |
| 14 | + * (ie, you must sell the stock before you buy again). |
| 15 | + * |
| 16 | + *************************************************************************** |
| 17 | + * {@link https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ } |
| 18 | + * @reference {@link https://leetcode.com/discuss/15153/a-clean-dp-solution-which-generalizes-to-k-transactions } |
| 19 | + */ |
| 20 | +package_188_BestTimeToBuyAndSellStockIV; |
| 21 | + |
| 22 | +/** see test {@link _188_BestTimeToBuyAndSellStockIV.SolutionTest } */ |
| 23 | +publicclassSolution { |
| 24 | + |
| 25 | +publicintmaxProfit(intk,int[]prices) { |
| 26 | +intn =prices.length; |
| 27 | +int[][]f =newint[k +1][n]; |
| 28 | +for (inti =0;i <k;i++) { |
| 29 | +inttmpMax =f[k -1][0] -prices[0]; |
| 30 | +for (intj =1;j <n;j++) { |
| 31 | +f[i][j] =Math.max(f[i][j -1],prices[j] +tmpMax); |
| 32 | +tmpMax =Math.max(tmpMax,f[i -1][j] -prices[j]); |
| 33 | + } |
| 34 | + } |
| 35 | +returnk; |
| 36 | + } |
| 37 | + |
| 38 | +} |