[leetcode]121.Best Time to Buy and Sell Stock|差分数组&Dynamic Programming

题目

[leetcode]121.Best Time to Buy and Sell Stock|差分数组&Dynamic Programming_第1张图片
题目分析:
这道题也是求最值,所以用了动态规划。直接用prices求动态规划数组好像不太行,所以我就加了一个差分数组diff,然后按照求最大subarray和的方法,求得结果。

代码

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

Runtime: 1 ms, faster than 80.34% of Java online submissions for Best Time to Buy and Sell Stock.
Memory Usage: 37.1 MB, less than 100.00% of Java online submissions for Best Time to Buy and Sell Stock.

你可能感兴趣的:([leetcode]121.Best Time to Buy and Sell Stock|差分数组&Dynamic Programming)