121. Best Time to Buy and Sell Stock [Easy]

股票问题,经典动态规划 

/**
 * 动态规划,用数组
 * Runtime: 3 ms, faster than 25.53%
 * Memory Usage: 55 MB, less than 25.36%
 */
class Solution {
    public int maxProfit(int[] prices) {
        int[] dp = new int[prices.length];
        int min = prices[0];
        for (int i = 1; i < prices.length; i++) {
            min = Math.min(min, prices[i]);
            dp[i] = Math.max(dp[i - 1], prices[i] - min);
        }
        return dp[prices.length - 1];
    }
}
/**
 * 动态规划,不用数组
 * Runtime: 2 ms, faster than 65.98%
 * Memory Usage: 52 MB, less than 71.07% 
 */
class Solution {
    public int maxProfit(int[] prices) {
        int min = prices[0], res = 0;
        for (int i = 1; i < prices.length; i++) { // 或者用for (int price : prices),跑出来效果一模一样
            min = Math.min(min, prices[i]);
            res = Math.max(res, prices[i] - min);
        }
        return res;
    }
}
上一篇:如果数据是通过Javascript加载的,如何使用php Goutte和Guzzle进行爬网?


下一篇:CF 867E. Buy Low Sell High(反悔贪心+堆)