zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    The Django Book学习笔记 04 模板
    The Django Book学习笔记
    Python标准库 datetime
    Python %s和%r的区别
    Python转载
    Python while 1 和 while True 速度比较
    Git 时光穿梭鸡 删除文件 以及批量删除文件
    git reset soft,hard,mixed之区别深解
    Git 时光穿梭鸡 撤销修改
    Git 时光穿梭鸡 管理修改
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5694994.html
Copyright © 2011-2022 走看看