File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int maxProfit (int k , int [] prices ) {
3
+ int [][][] dp = new int [prices .length + 1 ][k + 1 ][2 ];
4
+
5
+ for (int day = prices .length - 1 ; day >= 0 ; day --) {
6
+ for (int transactionsRemaining = 1 ; transactionsRemaining <= k ; transactionsRemaining ++) {
7
+ for (int holding = 0 ; holding < 2 ; holding ++) {
8
+ int noAction = dp [day +1 ][transactionsRemaining ][holding ];
9
+ int action ;
10
+
11
+ // holding == 1 is sell, otherwise buy
12
+ if (holding == 1 ) {
13
+ action = prices [day ] + dp [day +1 ][transactionsRemaining -1 ][0 ];
14
+ } else {
15
+ action = -prices [day ] + dp [day +1 ][transactionsRemaining ][1 ];
16
+ }
17
+
18
+ dp [day ][transactionsRemaining ][holding ] = Math .max (action , noAction );
19
+ }
20
+ }
21
+ }
22
+
23
+ return dp [0 ][k ][0 ];
24
+ }
25
+ }
You can’t perform that action at this time.
0 commit comments