Open Tcdian opened 3 years ago
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
if (prices.length === 0) {
return 0;
}
const hold = [-prices[0]];
const sell = [-Infinity];
const wait = [0];
for (let i = 1; i < prices.length; i++) {
hold[i] = Math.max(hold[i - 1], wait[i - 1] - prices[i]);
sell[i] = hold[i - 1] + prices[i];
wait[i] = Math.max(sell[i - 1], wait[i - 1]);
}
return Math.max(sell[prices.length - 1], wait[prices.length - 1]);
};
function maxProfit(prices: number[]): number {
if (prices.length === 0) {
return 0;
}
const hold = [-prices[0]];
const sell = [-Infinity];
const wait = [0];
for (let i = 1; i < prices.length; i++) {
hold[i] = Math.max(hold[i - 1], wait[i - 1] - prices[i]);
sell[i] = hold[i - 1] + prices[i];
wait[i] = Math.max(sell[i - 1], wait[i - 1]);
}
return Math.max(sell[prices.length - 1], wait[prices.length - 1]);
};
309. Best Time to Buy and Sell Stock with Cooldown
给定一个整数数组,其中第
i
个元素代表了第i
天的股票价格 。设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):
Example