Jerry's Blog

Recording what I learned everyday

View on GitHub


20 November 2020

LeetCode(309) -- Best Time to Buy and Sell Stock with Cooldown

by Jerry Zhang

Problem

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:

Example:

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

Solution

class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length == 0) {
            return 0;
        }
        int n = prices.length;
        int[][] f = new int[n][3];
        f[0][0] = -prices[0];
        for (int i = 1; i < n; i++) {
            // f[i][0]: 手上持有股票的最大收益
            // f[i][1]: 手上不持有股票,并且处于冷冻期中的累计最大收益
            // f[i][2]: 手上不持有股票,并且不在冷冻期中的累计最大收益
            f[i][0] = Math.max(f[i - 1][0], f[i - 1][2] - prices[i]);
            f[i][1] = f[i - 1][0] + prices[i];
            f[i][2] = Math.max(f[i - 1][1], f[i - 1][2]);
        }
        return Math.max(f[n - 1][1], f[n - 1][2]);
    }
}

50%

The Best Solution

class Solution {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        if (prices == null || n < 2) {
            return 0;
        }
        int[] buy = new int[n];
        int[] sell = new int[n];
        buy[0] = -prices[0];
        buy[1] = Math.max(buy[0], -prices[1]);
        sell[1] = Math.max(sell[0], prices[1] - prices[0]);
        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], prices[i] + buy[i - 1]);
        }
        return sell[n - 1];
    }
}

记录下在某一天买或者卖能得到的最大收益。

tags: LeetCode