codeTop100题(17)121. 买卖股票的最佳时机

72 阅读1分钟

1. 题目

121. 买卖股票的最佳时机

2. 分析

尝试一下动态规划是否可以解决:

  • 确定dp数组含义,需要两个数组;a当天能得到的最大收益,b当天之前的最低价格
  • 公式:a[i] = max(a[i-1], nums[i]-b[i-1]);
  • 初始化:a[0] = 0; b[0] = nums[i];
  • 遍历属性nums 1到length-1

但是我们发现,这两个dp数组在遍历过程中都只使用了i-1的值,所以我们考虑,有max , min来替代两个数组

3. 代码

public int maxProfit(int[] prices) {
    if (0 == prices.length) {
        return 0;
    }
    int min = prices[0];
    int max = 0;

    for (int i = 1; i < prices.length; i++) {
        min = Math.min(min, prices[i]);
        max = Math.max(max, prices[i] - min);
    }
    return max;
}