Leetcode 309. Best Time to Buy and Sell Stock with Cooldown

来源:互联网 发布:8000电钢琴推荐 知乎 编辑:程序博客网 时间:2024/06/06 00:00

问题描述

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 = 3transactions = [buy, sell, cooldown, buy, sell]

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

问题分析:
题意:每次只能买入一个股票,每个时间点最多只能持有一个股票,当卖出股票之后必须歇一天之后重新进行交易。
如果问共有多少种交易,则是卡特兰数。然而问题问的是能够获得的最大收益。
如果前一天持有股票,则今天可以卖掉,如果前一天不持有股票,则判断前一天是否是cooldown。所以必须知道两个信息,即什么时候购买股票,什么时候卖掉股票。
用两个数组:sells[i]表示第i天持有股票,buys[i]表示第i天不持有股票。
状态转移方程:
sells[i]=Max(sells[i-1],buys[i-1]+prices[i])
buys[i]=Max(buys[i-1],sells[i-2]-prices[i])

代码如下:

    public int maxProfit(int[] prices) {        int n=prices.length;        if(n<=1)            return 0;        int[]sells=new int[n];        int[]buys=new int[n];        sells[1]=Math.max(0,prices[1]-prices[0]);        buys[0]=-prices[0];        buys[1]=Math.max(-prices[0],-prices[1]);        for(int i=2;i<n;i++){            sells[i]=Math.max(buys[i-1]+prices[i],sells[i-1]);            buys[i]=Math.max(sells[i-2]-prices[i],buys[i-1]);        }        return sells[n-1];    }
阅读全文
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 桌面没有qq图标怎么办 江湖风云录卡了怎么办? 江湖风云录闪退怎么办 借呗开通不了怎么办 查不到全国学籍怎么办 六福的会员卡怎么办 夏天小腿皮肤痒怎么办 夏天皮肤容易痒怎么办 夏天身上老是痒怎么办 龙虾塘没水草怎么办 龙虾塘水草太多怎么办 电脑卡死黑屏怎么办 手机进入游戏时闪退怎么办? lol画面卡住了怎么办 PLSQL DEV未响应怎么办 英雄联盟载入慢怎么办 玩英雄联盟黑屏怎么办 电脑玩lol死机怎么办 输入不支援黑屏怎么办 一加玩游戏登录不了怎么办 网络连接错误711怎么办 电脑网络错误651怎么办 打游戏内存不够怎么办 电脑超频后黑屏怎么办 玩lol显示器超频怎么办 win10显示器超频黑屏怎么办 电脑开机显示超频怎么办 玩英雄联盟网卡怎么办 英雄联盟超屏怎么办 三星手机基带未知怎么办 显卡进桌面黑屏怎么办 电脑开机黑屏怎么办打开 ap黑屏打不开了怎么办 老人机屏幕变黑怎么办 电脑一直弹网页怎么办 电脑一直跳网页怎么办 电脑网页一直转圈怎么办 消费者联盟闪退怎么办 门卡住了打不开怎么办 悦平台出现bug怎么办 lol开不了全屏怎么办