随想录Day49 | 121. 买卖股票的最佳时机、122. 买卖股票的最佳时机 II | 动态规划

69 阅读2分钟

121. 买卖股票的最佳时机

题目链接:121. 买卖股票的最佳时机

思路:

动规五部曲 

1.确定dp数组以及下标的含义

dp[i][0]:第i天手中没有股票的最高金额 dp[i][1]:第i天手中有股票的最高金额

2.确定递推公式

dp[i][0] = Math.max(dp[i - 1][0] (昨天也没持有), dp[i - 1][1] + prices[i] (昨天有今天卖了))。 dp[i][1] = Math.max(dp[i - 1][1] (昨天也持有), - prices[i] (之前没有今天买入))。

3.dp数组如何初始化

dp[0][0] = 0 dp[0][1] = -prices[0];

4.确定遍历顺序

从前向后遍历

代码:

class Solution {
    public int maxProfit(int[] prices) {
        // dp[i][1]表示第i天持有股票的最大收益
        // dp[i][0]表示第i天不持有股票的最大收益
        int[][] dp = new int[prices.length][2];
        dp[0][0] = 0;
        dp[0][1] = -prices[0];
        for (int i = 1; i < prices.length; i++) {
            dp[i][1] = Math.max(dp[i - 1][0], - prices[i]);
            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
        }
        return dp[prices.length - 1][1];
    }
}

122. 买卖股票的最佳时机 II

题目链接:122. 买卖股票的最佳时机 II

思路:

在121. 买卖股票的最佳时机中,因为股票全程只能买卖一次,所以如果买入股票,那么第i天持有股票即dp[i][0]一定就是 -prices[i]。

而本题,因为一只股票可以买卖多次,所以当第i天买入股票的时候,所持有的现金可能有之前买卖过的利润。

那么第i天持有股票即dp[i][0],如果是第i天买入股票,所得现金就是昨天不持有股票的所得现金 减去 今天的股票价格 即:dp[i - 1][1] - prices[i]。

class Solution {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        int[][] dp = new int[n][2];     // 创建二维数组存储状态
        dp[0][0] = 0;                   // 初始状态
        dp[0][1] = -prices[0];
        for (int i = 1; i < n; ++i) {
            // 第 i 天,没有股票
            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);   
            // 第 i 天,持有股票
            dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);    
        }
        // 卖出股票收益高于持有股票收益,因此取[0]
        return dp[n - 1][0];    
    }
}