zoukankan      html  css  js  c++  java
  • LeetCode 309. 最佳买卖股票时机含冷冻期

    题目链接

    309. 最佳买卖股票时机含冷冻期

    题目分析

    非常经典的股票买卖问题了,股票一共有两种状态:天数和持有或者不持有。我们只需要处理好base cases就可以顺着推下去做了。这里要注意它含有1天的冷却期,那么我们在处理持有股票的时候要注意,买入股票必须要在前天不持有股票的情况下进行了~

    代码实现

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

    总结

    股票问题非常的经典,LC上有6道股票DP问题,非常值得深究。这里贴一个股票问题通解的题解

  • 相关阅读:
    LeetCode "Sum Root to Leaf Numbers"
    LeetCode "Single Number"
    POJ #1033
    POJ #1011
    POJ #2411
    POJ #1276
    POJ #1260
    POJ #1221
    POJ #1080
    POJ #1050
  • 原文地址:https://www.cnblogs.com/ZJPaang/p/13277534.html
Copyright © 2011-2022 走看看