File tree 1 file changed +33
-0
lines changed
1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ //这道题基本上跟123.Best Time to Buy and Sell Stock III一模一样。
2
+ //唯一需要注意的一个条件就是我们发现如果k过半的话,那么我们足够收集到所有的profit。所以累加即可。
3
+ //剩下的dp问题就跟123完全一样了。详情请看那个文件: 123_maxProfit.java
4
+
5
+ public class Solution {
6
+ public int maxProfit (int k , int [] prices ) {
7
+ if (prices == null || prices .length == 0 ) return 0 ;
8
+ int len = prices .length ;
9
+ if (k > len /2 ) return quickSolve (prices );//Very important!!!! if k > len/2, we can collect all profits.
10
+
11
+ int [][] dp = new int [k +1 ][prices .length ];
12
+ int res = 0 ;
13
+ for (int i = 1 ; i <= k ; i ++){
14
+ int tmpMax = dp [i -1 ][0 ]-prices [0 ];
15
+ for (int j = 1 ; j < prices .length ; j ++){
16
+ dp [i ][j ] = Math .max (dp [i ][j -1 ], prices [j ]+tmpMax );
17
+ tmpMax = Math .max (tmpMax , dp [i -1 ][j ]-prices [j ]);
18
+ res = Math .max (res , dp [i ][j ]);
19
+ }
20
+ }
21
+ return res ;
22
+ }
23
+
24
+ public int quickSolve (int [] prices ){
25
+ int profit = 0 ;
26
+ int i = 1 ;
27
+ while (i < prices .length ){
28
+ if (prices [i ] > prices [i -1 ]) profit +=(prices [i ]-prices [i -1 ]);
29
+ i ++;
30
+ }
31
+ return profit ;
32
+ }
33
+ }
You can’t perform that action at this time.
0 commit comments