leetcode309最佳买卖股票时机含冷冻期

leetcode 309 Best Time to Buy and Sell Stock with Cooldown

Posted by BY on July 7, 2020

前言

持续更新了

正文

问题来源

本问题来自leetcode上的309题。

问题描述

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

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

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

示例 1:

输入: [1,2,3,0,2]
输出: 3 
解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]

分析:

sell代表当天未持股,且为当天卖出的;cooldown代表当天未持股,且是本来就没有;buy代表当天持股,且不卖出。

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}

func maxProfit(prices []int) int {
    if len(prices) == 0 {
        return 0
    }
    sell := make([]int, len(prices))
    cooldown := make([]int, len(prices))
    buy := make([]int, len(prices))
    sell[0] = 0
    cooldown[0] = 0
    buy[0] = -prices[0]
    for i := 1; i < len(prices); i++ {
        sell[i] = buy[i-1] + prices[i]
        cooldown[i] = max(cooldown[i-1], sell[i-1])
        buy[i] = max(buy[i-1], cooldown[i-1]-prices[i])
    }
    return max(cooldown[len(prices)-1], sell[len(prices)-1])
}

优化些空间

func maxProfit(prices []int) int {
    if len(prices) == 0 {
        return 0
    }
    sell := 0
    cooldown := 0
    buy := -prices[0]
    for i := 1; i < len(prices); i++ {
        // 三个赋值语句顺序不能换
        buy = max(buy, cooldown-prices[i]) 
        cooldown = max(cooldown, sell) 
        sell = buy + prices[i]
    }
    return max(cooldown, sell)
}

总结:

勤思考。

结语

不管怎么样好好加油。