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

分析

难度 中
来源 https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
题目
Say you have an array for which the i th 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]

解答

Runtime: 5 ms, faster than 100.00% of Java online submissions for Best Time to Buy and Sell Stock with Cooldown.
Memory Usage: 38.6 MB, less than 6.94% of Java online submissions for Best Time to Buy and Sell Stock with Cooldown.

package LeetCode;

public class L309_BestTimetoBuyandSellStockwithCooldown {
    public int maxProfit(int[] prices) {
        if(prices==null||prices.length<=1)//等于1的话没有卖出操作,也就没有利润。
            return 0;
        /*
        两种类型的利润,
        第一种,第i天卖出
        第二种,第i天歇着(卖出后,没有买入。不卖出是不能算利润的。可以是冷却,也可以是不操作)
         */
        int sellProfit=0,restProfit=0,lastSellProfit=0;//lastSellProfit记录上一步的卖出利润
        for(int i=1;i<prices.length;i++){//贪心算法。
            lastSellProfit=sellProfit;//i-1天的卖出利润。
            sellProfit=Math.max(sellProfit+prices[i]-prices[i-1],restProfit);//前边表示撤销前一天的售出,改今天售出的利润;后一个表示到第i-1天的最大利润。第i天售出不可能第i-1天rest的利润。
            restProfit=Math.max(restProfit,lastSellProfit);//第i天rest的利润(跟i-1天卖出做比较)。
        }
        return Math.max(sellProfit,restProfit);//返回最后一天的卖出利润和休息利润中较大的
    }
    public static void main(String[] args){
        L309_BestTimetoBuyandSellStockwithCooldown l309=new L309_BestTimetoBuyandSellStockwithCooldown();
        int[] prices={1,2,3,0,2};
        System.out.println(l309.maxProfit(prices));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值