资讯专栏INFORMATION COLUMN

309. Best Time to Buy and Sell Stock with Cooldown

sorra / 2204人阅读

摘要:题目链接来解,要用两个分别表示现在的操作是还是,优化空间用滚动数组,或者几个

309. Best Time to Buy and Sell Stock with Cooldown

题目链接:https://leetcode.com/problems...

dp来解,要用两个dp array分别表示现在的操作是buy还是sell,优化空间用滚动数组,或者几个int

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length == 0) return 0;
        /* buy[i] = Math.max(sell[i-2]-prices[i], buy[i-1])
         * sell[i] = Math.max(sell[i-1], buy[i-1] + prices[i])
         */
        int preBuy = Integer.MIN_VALUE, curBuy = Integer.MIN_VALUE;
        int preSell = 0, curSell = 0;
        for(int price : prices) {
            preBuy = curBuy;
            curBuy = Math.max(preSell - price, preBuy);
            preSell = curSell;
            curSell = Math.max(preSell, preBuy + price);
        }
        
        return curSell;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/66666.html

相关文章

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

    摘要:示例输入输出解释对应的交易状态为买入卖出冷冻期买入卖出思路这道题使用动态规划。状态表示当天休息能够获得的最大价值,表示当天持有股票能够获得的最大价值,表示当天持有股票能够获得的最大价值。 Description Say you have an array for which the ith element is the price of a given stock on day i. ...

    刘明 评论0 收藏0
  • [LeetCode]Best Time to Buy and Sell Stock with Coo

    摘要:分析因为当前日期买卖股票会受到之前日期买卖股票行为的影响,首先考虑到用解决。所以我们可以用两个数组分别记录当前持股跟未持股的状态。 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 ...

    xcc3641 评论0 收藏0
  • 121. Best Time to Buy and Sell Stock

    121. Best Time to Buy and Sell Stock Say you have an array for which the ith element is the price of a given stock on day i.If you were only permitted to complete at most one transaction (i.e., buy on...

    Tecode 评论0 收藏0
  • Best Time To Buy And Sell Stock 买卖股票最佳时机

    摘要:关键字,,算法,,动态规划,上关于主题的题目有四个这四个题目难度依次递增。其中第四个问题是寻求一个通解,在给定和最大买卖次数的情况下,求最大收益。首先大致的解题方向是动态规划,这个应该不难想到。之后就是怎么找到状态,怎么列状态转移方程。 关键字:leetcode,Best Time To Buy And Sell Stock,算法,algorithm,动态规划,dynamic prog...

    elliott_hu 评论0 收藏0
  • leetcode 121 Best Time to Buy and Sell Stock

    摘要:求可能的最大利润题目给了两个例子最大利润就是进价为,卖价为的时候,利润为在这个案例中,进价一直高于售价,所以无法成交,返回。主要注意一下,先买入才能卖出卖价一定要比买入价格高才能成交就可以了。 题目详情 Say you have an array for which the ith element is the price of a given stock on day i.If yo...

    QLQ 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<