算法: 加冷冻期时间的买卖股票309. Best Time to Buy and Sell Stock with Cooldown

Posted AI架构师易筋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法: 加冷冻期时间的买卖股票309. Best Time to Buy and Sell Stock with Cooldown相关的知识,希望对你有一定的参考价值。

309. Best Time to Buy and Sell Stock with Cooldown

ou are given an array prices where prices[i] is the price of a given stock on the ith day.

Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:

  • After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

Example 1:

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

Example 2:

Input: prices = [1]
Output: 0

Constraints:

  • 1 <= prices.length <= 5000
  • 0 <= prices[i] <= 1000

动态规划解法


根据您可以采取的操作,共有三种状态。

因此,从那里,您现在可以在时间 i 的状态下获得利润:

s0[i] = max(s0[i - 1], s2[i - 1]); // Stay at s0, or rest from s2
s1[i] = max(s1[i - 1], s0[i - 1] - prices[i]); // Stay at s1, or buy from s0
s2[i] = s1[i - 1] + prices[i]; // Only one way from s1

然后,您只需找到 s0[n] 和 s2[n] 的最大值,因为它们将是我们需要的最大利润(没有人可以购买股票并留下更多的利润卖给右边:))

定义基本情况:

s0[0] = 0; // At the start, you don't have any stock if you just rest
s1[0] = -prices[0]; // After buy, you should have -prices[0] profit. Be positive!
s2[0] = INT_MIN; // Lower base case

这是代码:D

class Solution 
    public int maxProfit(int[] prices) 
        int n = prices.length;
        if (n <= 1) return 0;
        int[] s0 = new int[n];
        int[] s1 = new int[n];
        int[] s2 = new int[n];
        s0[0] = 0;
        s1[0] = -prices[0];
        s2[0] = Integer.MIN_VALUE;
        for (int i = 1; i < n; i++) 
            s0[i] = Math.max(s0[i - 1], s2[i - 1]);
            s1[i] = Math.max(s1[i - 1], s0[i - 1] - prices[i]);
            s2[i] = s1[i - 1] + prices[i];
        
        
        return Math.max(s0[n - 1], s2[n - 1]);
    

参考

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/75928/Share-my-DP-solution-(By-State-Machine-Thinking)

以上是关于算法: 加冷冻期时间的买卖股票309. Best Time to Buy and Sell Stock with Cooldown的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 0309. 最佳买卖股票时机含冷冻期

309. 最佳买卖股票时机含冷冻期 DP

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

力扣309.买卖股拍哦最佳时机含冷冻期

力扣309.买卖股拍哦最佳时机含冷冻期

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