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

1
class Solution {
2
public int maxProfit(int[] prices) {
3

4
int n = prices.length;
5

6
int[][] dp = new int[n + 2][2];
7

8
for (int index = n - 1; index >= 0; index--) {
9
for (int buy = 0; buy <= 1; buy++) {
10

11
int profit = 0;
12

13
if (buy == 0) { // buy stocks
14
profit = Math.max(-prices[index] + dp[index + 1][1], 0 + dp[index + 1][0]);
15
}
16
if (buy == 1) { // we can sell stocks
17
profit = Math.max(prices[index] + dp[index + 2][0], 0 + dp[index + 1][1]);
18
}
19
dp[index][buy] = profit;
20
}
21
}
22
return dp[0][0];
23
}
24
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0