LeetCode 309. Best Time to Buy and Sell Stock with Cooldown--Java解法-賣股票系列題目

此文首發於我的Jekyll博客:zhang0peter的個人博客


LeetCode題解文章分類:LeetCode題解文章集合
LeetCode 所有題目總結:LeetCode 所有題目總結


題目地址:Best Time to Buy and Sell Stock with Cooldown - LeetCode


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:

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:

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

這道題目的區別跟之前的買賣股票的題目區別在於賣了之後要停一天。

最容易想到的是貪心,但會發現貪心不能解決問題。

因爲後面一個狀態跟前面一個狀態有關,應該用動態規劃解決。

因爲之前賣了需要冷卻一天,所以需要另外一個變量來存

第n個狀態應該與n-1和n-2個狀態有關

下面先把解法列出來。

Java 解法如下:

class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length <= 1) {
            return 0;
        }
        /**
         there can be two types of profit we need to track
         sellProf[i] - profit earned by selling on ith day
         restProf[i] - profit earned by resting on ith day
         */
        int sellProf = 0;
        int restProf = 0;
        int lastProf = 0;
        for (int i = 1; i < prices.length; i++) {
            lastProf = sellProf;
            //the current sellProf is either by selling on ith day or by resting on ith day
            sellProf = Math.max(sellProf + prices[i] - prices[i - 1], restProf);
            restProf = Math.max(lastProf, restProf);
        }
        return Math.max(sellProf, restProf);
    }
}

下面以[1, 2, 3, 0, 2]爲例:

初始值 1 2 3 0 2
sellProf 0 1 2 1 3
restProf 0 0 1 2 2
lastProf 0 0 1 2 1

這裏有2個主要的變量,一個是sellProf,另一個是restProf.

sellProf變量意味着當前賣掉股票的總收入或者昨天休息的總收入。這裏有個難點,那就是如果你昨天賣了股票,今天又賣股票,實際意味着前天賣的股票,今天賣了。

restProf變量意味着昨天賣掉股票,今天繼續休息的總收入或者昨天休息的總收入。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章