class Solution:
def maxProfit(self, prices):
if not prices:
return 0
n = len(prices)
hold = [0] * n
sold = [0] * n
rest = [0] * n
hold[0] = -prices[0]
sold[0] = 0
rest[0] = 0
for i in range(1, n):
hold[i] = max(hold[i-1], rest[i-1] - prices[i])
sold[i] = hold[i-1] + prices[i]
rest[i] = max(rest[i-1], sold[i-1])
return max(sold[-1], rest[-1])
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.empty()) return 0;
int n = prices.size();
vector<int> hold(n, 0), sold(n, 0), rest(n, 0);
hold[0] = -prices[0];
sold[0] = 0;
rest[0] = 0;
for (int i = 1; i < n; ++i) {
hold[i] = max(hold[i-1], rest[i-1] - prices[i]);
sold[i] = hold[i-1] + prices[i];
rest[i] = max(rest[i-1], sold[i-1]);
}
return max(sold[n-1], rest[n-1]);
}
};
class Solution {
public int maxProfit(int[] prices) {
if (prices.length == 0) return 0;
int n = prices.length;
int[] hold = new int[n];
int[] sold = new int[n];
int[] rest = new int[n];
hold[0] = -prices[0];
sold[0] = 0;
rest[0] = 0;
for (int i = 1; i < n; i++) {
hold[i] = Math.max(hold[i-1], rest[i-1] - prices[i]);
sold[i] = hold[i-1] + prices[i];
rest[i] = Math.max(rest[i-1], sold[i-1]);
}
return Math.max(sold[n-1], rest[n-1]);
}
}
var maxProfit = function(prices) {
if (prices.length === 0) return 0;
const n = prices.length;
let hold = new Array(n).fill(0);
let sold = new Array(n).fill(0);
let rest = new Array(n).fill(0);
hold[0] = -prices[0];
sold[0] = 0;
rest[0] = 0;
for (let i = 1; i < n; i++) {
hold[i] = Math.max(hold[i-1], rest[i-1] - prices[i]);
sold[i] = hold[i-1] + prices[i];
rest[i] = Math.max(rest[i-1], sold[i-1]);
}
return Math.max(sold[n-1], rest[n-1]);
};
prices
, where prices[i]
is the price of a given stock on day i
. You want to maximize your profit by choosing a sequence of buy and sell operations, but with these constraints:
prices
array, and you must not reuse elements or violate the cooldown constraint.
i
.i
.i
(i.e., not holding and not just sold).sold[n-1]
and rest[n-1]
on the last day, since we can't end with a "hold" (that would mean we still own stock).
hold[0] = -prices[0]
(buy on day 0)sold[0] = 0
rest[0] = 0
prices = [1,2,3,0,2]
.