• LeetCode-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]
    

    Credits:
    Special thanks to @dietpepsi for adding this problem and creating all test cases.

    Analysis:

    Always consider two situations: hold[i]: we have stock on hand at ith day; unhold[i]: we do not have stock on hand at ith day.

    Solution:

     1 public class Solution {
     2     public int maxProfit(int[] prices) {
     3         if (prices.length<2) return 0;
     4 
     5         int[] hold = new int[prices.length];
     6         int[] unhold = new int[prices.length];
     7 
     8         hold[0] = -prices[0];
     9         unhold[0] = 0;
    10         hold[1] = Math.max(hold[0],-prices[1]);
    11         unhold[1] = Math.max(0,hold[0]+prices[1]);
    12 
    13         for (int i=2;i<prices.length;i++){
    14             hold[i] = Math.max(hold[i-1], unhold[i-2]-prices[i]);
    15             unhold[i] = Math.max(unhold[i-1],hold[i-1]+prices[i]);
    16         }
    17 
    18         return Math.max(hold[prices.length-1],unhold[prices.length-1]);
    19     }
    20 }
  • 相关阅读:
    啥叫ORM
    git reset --hard HEAD^ 在cmd中执行报错
    windows下生成文件目录树
    批量解决win10图标上有两个蓝色箭头的方法
    Sublime Text 3 安装包
    Sublime Text 3 部分安装过程记录
    sense8影评摘抄
    如何取消chrome的自动翻译
    把本地仓库同步到github上去
    关于PDF阅读器
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5694994.html
Copyright © 2020-2023  润新知