• 0309. Best Time to Buy and Sell Stock with Cooldown (M)


    Best Time to Buy and Sell Stock with Cooldown (M)

    题目

    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]
    

    题意

    股票买卖问题。给定每一天的股票价格以及相应规则:同一天只能买或卖,卖股票必须在买股票之后,可以执行多次买卖交易,但每次卖股票后隔一天才能再次买股票。要求计算能得到的最大利润。

    思路

    动态规划。定义两个数组:

    • (hold[i]) 表示在第i天手头上仍有股票未出售时已经得到的最大利润
    • (sold[i]) 表示在第i天未持有任何股票时已经得到的最大利润

    对于(hold[i]),有两种情况导致第i天仍持有股票:

    1. 恰好在第i天购入股票。因为冷却时间的存在,必须在第i-2天或之前就卖掉上一个持有的股票;
    2. 在第i-1天或之前就已经持有了股票,而在第i天没有做任何事。

    对于(sold[i]),同样有两种情况导致第i天手头没有股票:

    1. 恰好在第i天卖掉了股票;
    2. 在第i-1天或之前就已经卖掉了股票,而在第i天没有做任何事。

    综合以上可以得到两个递推公式:

    [egin{cases} hold[i]=max(sold[i-2]-prices[i], hold[i-1])\\ sold[i]=max(hold[i-1]+prices[i], sold[i-1]) end{cases} ]


    代码实现

    Java

    class Solution {
        public int maxProfit(int[] prices) {
            if (prices.length < 2) return 0;
        
            int[] hold = new int[prices.length];
            int[] sold = new int[prices.length];
            hold[0] = -prices[0];
            for (int i = 1; i < prices.length; i++) {
                hold[i] = Math.max(i == 1 ? -prices[1] : sold[i - 2] - prices[i], hold[i - 1]);
                sold[i] = Math.max(hold[i - 1] + prices[i], sold[i - 1]);
            }
            return sold[sold.length - 1];
        }
    }
    

    参考

    【LeetCode】309. Best Time to Buy and Sell Stock with Cooldown 解题报告(Python & C++)

  • 相关阅读:
    长连接与短连接
    服务器配置tomact service
    数据库权限表设计
    VPS搭建离线下载服务器——后网盘时代
    Unix socket的准备(一)
    LeetCode 650
    C++11获取线程的返回值
    柔性数组成员——不定长的数据结构
    看懂类图——UML类图基础
    Java类初始化顺序
  • 原文地址:https://www.cnblogs.com/mapoos/p/13402341.html
Copyright © 2020-2023  润新知