算法修炼Day49|

69 阅读1分钟
题目:121. 买卖股票的最佳时机 - 力扣(LeetCode)
代码实现:
class Solution {
    public int maxProfit(int[] prices) {
        // 每天的状态有两种:持有和不持有
        int len = prices.length;
        int[][] dp = new int[len][2];
        dp[0][0] = 0; // 不持有
        dp[0][1] = -prices[0]; // 持有
        for (int i = 1; i < len; 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], - prices[i]); // 持有:前一天持有,当天持有
        }
        return dp[len - 1][0];
    }
}
题目:122. 买卖股票的最佳时机 II - 力扣(LeetCode)
代码实现:
class Solution {
    public int maxProfit(int[] prices) {
        int ans = 0;
        for (int i = 1; i < prices.length; i++) {
            ans += Math.max(prices[i] - prices[i - 1], 0);
        }
        return ans;
    }
}