309. Best Time to Buy and Sell Stock with Cooldown

来源:互联网 发布:阿里云ecs教程 编辑:程序博客网 时间:2024/06/05 06:03

Say you have an array for which the ith element is the price of a given stock on dayi.

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:


public class Solution {    public int maxProfit(int[] prices) {                //buy[i]=max(buy[i-1],sell[i-2]-prices[i])在当前节点买入和之前所有可能买入节点的最大值        //sell[i]=max(sell[i-1],buy[i-1]+prices[i])在当前结点卖出和此节点以前所有节点卖出的最大值        //当前的buy和sell的最大值依赖前一个和前2个                 int n=prices.length;         //初始值,在刚刚开始时,之前的卖出得到的利润为0;之前的买入最大利润为负数的最大值。因为刚刚开始不可能是卖。        int pre_buy,buy=Integer.MIN_VALUE,pre_sell=0,sell=0;        //pre表示前一天买入和卖出,buy和sell表示当天买入和卖出        for(int i=0;i<n;i++){            pre_buy=buy;            buy=Math.max(pre_buy,pre_sell-prices[i]);            pre_sell=sell;            sell=Math.max(sell,pre_buy+prices[i]);        }        return sell;            }}



0 0
原创粉丝点击