Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

309. Best Time to Buy and Sell Stock with Cooldown #251

Open Tcdian opened 3 years ago

Tcdian commented 3 years ago

309. Best Time to Buy and Sell Stock with Cooldown

给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。​

设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):

Example

Input: [1,2,3,0,2]
Output: 3 
Explanation: transactions = [buy, sell, cooldown, buy, sell]
Tcdian commented 3 years ago

Solution

/**
 * @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]);
};