zoukankan      html  css  js  c++  java
  • 309. 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:

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

    sell是今天手里没有股票,sell[i] 的第一种可能:今天没动作跟昨天持股状态一样,也可以看作是前天卖了之后的cooldown期(也可能是股票价格高一直没买),总之今天妹有。第二种:股票是今天卖的,buy[i - 1] + prices[i], buy[i - 1]是前一天持股的最大利润,因为前一天持股,所以今天才有的卖。

    buy是今天手里有股票,可能是今天买的也可能是之前买的。buy[i]的第一种可能:buy[i - 1](昨天手里也有股票,今天啥都没干),第二种可能:sell[i - 2] - prices[i](前天卖了经过一天空窗期,今天买了股票)。

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

    初始值sell为0,意思是第一天卖掉的利润(买了再卖肯定是0)

    buy为-prices[0],意思是第一天买了的利润(肯定是-prices[0])。

  • 相关阅读:
    Picasa生成图片幻灯片页面图文教程
    Ubuntu下缓冲器溢出攻击实验(可以看看问题分析)
    redis源码笔记 aof
    redis源码笔记 bio
    redis源码笔记 slowlog
    记录一个字符数组和字符指针的不同
    redis源码笔记 rediscli.c
    redis源码笔记 redis对过期值的处理(in redis.c)
    redis源码笔记 有关LRU cache相关的代码
    redis源码笔记 initServer
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11653207.html
Copyright © 2011-2022 走看看