Best Time to Buy and Sell Stock with Transaction Fee LeetCode solution in Java

1
class Solution {
2
public int maxProfit(int[] prices, int fee) {
3
int[][] dp = new int[prices.length][2];
4
for (int[] a : dp) {
5
a[0] = -1;
6
a[1] = -1;
7
}
8
return profit(prices, fee, 0, 1, dp);
9
}
10

11
public int profit(int[] prices, int fee, int i, int buy, int[][] dp) {
12
if (i == prices.length) {
13
return 0;
14
}
15
if (dp[i][buy] != -1) {
16
return dp[i][buy];
17
}
18
int maxProfit = 0;
19
if (buy == 1) {
20
int yesBuy = profit(prices, fee, i + 1, 0, dp) - prices[i];
21
int noBuy = profit(prices, fee, i + 1, 1, dp);
22
maxProfit = Math.max(yesBuy, noBuy);
23
} else {
24
int yesSell = prices[i] - fee + profit(prices, fee, i + 1, 1, dp);
25
int noSell = profit(prices, fee, i + 1, 0, dp);
26
maxProfit = Math.max(yesSell, noSell);
27
}
28
return dp[i][buy] = maxProfit;
29
}
30
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0