File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
src/_188_BestTimeToBuyAndSellStockIV Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
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
+ public class Solution {
24
+
25
+ public int maxProfit (int k , int [] prices ) {
26
+ int n = prices .length ;
27
+ int [][] f = new int [k + 1 ][n ];
28
+ for (int i = 0 ; i < k ; i ++) {
29
+ int tmpMax = f [k - 1 ][0 ] - prices [0 ];
30
+ for (int j = 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
+ return k ;
36
+ }
37
+
38
+ }
You can’t perform that action at this time.
0 commit comments