• LeetCode 309. Best Time to Buy and Sell Stock with Cooldown


    原题链接在这里:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/

    题目:

    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:

    prices = [1, 2, 3, 0, 2]
    maxProfit = 3
    transactions = [buy, sell, cooldown, buy, sell]

    题解:

    Let buy[i] denotes maximum profit till index i, series of transactions ending with buy.

    Let sell[i] denotes maimum profit till index i, series of transactions ending with sell.

    There is a cooldown before buy again. buy[i] could happend after sell[i-2], not sell[i-1].

    Thus, buy[i] = Math.max(buy[i-1], sell[i-2]-prices[i]).

    If wanna sell a stock, must buy stock before. Thus sell[i] is calculated with buy[i-1].

    sell[i] = Math.max(sell[i-1], buy[i-1]+prices[i]).

    只用到了i-1, i-2两个之前的量,所以可以使用常量来代替数组.

    b0 as buy[i], b1 as buy[i-1].

    s0 as sell[i], s1 as sell[i-1], s2 as sell[i-2].

    Time Complexity: O(n). n = prices.length.

    Space: O(1). 

    AC Java:

     1 class Solution {
     2     public int maxProfit(int[] prices) {
     3         if(prices == null || prices.length < 2){
     4             return 0;
     5         }
     6         
     7         int b0 = -prices[0];
     8         int b1 = b0;
     9         int s2 = 0;
    10         int s1 = 0;
    11         int s0 = 0;
    12         for(int i = 1; i<prices.length; i++){
    13             b0 = Math.max(b1, s2-prices[i]);
    14             s0 = Math.max(s1, b1+prices[i]);
    15             
    16             b1 = b0;
    17             s2 = s1;
    18             s1 = s0;
    19         }
    20         
    21         return s0;
    22     }
    23 }
  • 相关阅读:
    [LeetCode] 222. Count Complete Tree Nodes Java
    [LeetCode] 199. Binary Tree Right Side View Java
    自动加载的两种办法
    Cannot switch on a value of type String for source level below 1.7. Only convertible int values or enum variables are permitted
    Java 面试
    Java 获取最近时间
    Java 倒序输出
    java 排序算法
    图片预览
    SSH三大框架的工作原理
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5285886.html
Copyright © 2020-2023  润新知