Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Tcdian opened this issue Jul 10, 2020 · 1 comment
Open

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

Tcdian opened this issue Jul 10, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented Jul 10, 2020

309. Best Time to Buy and Sell Stock with Cooldown

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

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

  • 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
  • 卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。

Example

Input: [1,2,3,0,2]
Output: 3 
Explanation: transactions = [buy, sell, cooldown, buy, sell]
@Tcdian
Copy link
Owner Author

Tcdian commented Jul 10, 2020

Solution

  • JavaScript 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]);
};
  • TypeScript Solution
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]);
};

Tcdian pushed a commit to Tcdian/LeetCode that referenced this issue Jul 11, 2020
@Tcdian Tcdian removed the Classic label Jul 30, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant