-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_0309BestTimeToBuyAndSellStockWithCoolDown.java
More file actions
52 lines (43 loc) · 1.57 KB
/
_0309BestTimeToBuyAndSellStockWithCoolDown.java
File metadata and controls
52 lines (43 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.heatwave.leetcode.problems;
public class _0309BestTimeToBuyAndSellStockWithCoolDown {
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
if (n < 2) {
return 0;
}
int[] buy = new int[n];
int[] sell = new int[n];
buy[0] = -prices[0];
buy[1] = Math.max(-prices[0], -prices[1]);
sell[0] = 0;
sell[1] = Math.max(0, buy[0] + prices[1]);
for (int i = 2; i < n; i++) {
buy[i] = Math.max(buy[i - 1], sell[i - 2] - prices[i]);
sell[i] = Math.max(sell[i - 1], buy[i - 1] + prices[i]);
}
return sell[n - 1];
}
}
class SolutionMemoryOptimization {
public int maxProfit(int[] prices) {
int n = prices.length;
if (n < 2) {
return 0;
}
int buyYesterday = Math.max(-prices[0], -prices[1]);
int buyToday;
int sellTheDayBeforeYesterday = 0;
int sellYesterday = Math.max(0, buyYesterday + prices[1]);
int sellToday = 0;
for (int i = 2; i < n; i++) {
buyToday = Math.max(buyYesterday, sellTheDayBeforeYesterday - prices[i]);
sellToday = Math.max(sellYesterday, buyYesterday + prices[i]);
sellTheDayBeforeYesterday = sellYesterday;
sellYesterday = sellToday;
buyYesterday = buyToday;
}
return sellYesterday;
}
}
}