leetCode 编号122

10 阅读2分钟

122. 买卖股票的最佳时机 II:给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。

在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。

返回 你能获得的 最大 利润 

方法一
思路:
  1. 你能获得的 最大 利润,并不是某一笔交易的最大利润,而是所有交易的利润之和,121题中可以知道,某一笔求最大利润只需要,双指针找到 最大值 - 最小值 就行,同理所有的利润之和最大值,我们只需要将一整个数组,分解成一个个利润最大的小数组,最后将所有小数组的最大利润 相加 即可
  2. 小数组的分界点如何划分呢?只要 当前项 > 后一项 ,我们就可以以当前项为结尾划分出一个小数组了,因为后一个小数组的 最大值 - 当前项 的值,肯定是 小于 它的 最大值 - 后一项 的,毕竟 后一项 < 当前项
  3. 如果是 递增数组 从头到尾只有一个最大利润,所以需要特殊判断
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function (prices) {
    let result = 0
    let minValue = prices[0]
    for (let maxIndex = 1; maxIndex < prices.length; maxIndex++) {
        if (prices[maxIndex] < minValue) {
            minValue = prices[maxIndex]
        }
        if (prices[maxIndex] > prices[maxIndex + 1] || maxIndex == prices.length - 1) {
            result = result + Math.max(prices[maxIndex] - minValue, 0)
            minValue = prices[maxIndex + 1]
            maxIndex++
        }
    }
    return result
};
方法二( 推荐 贪心算法:官方题解
思路:
  1. [1, 2, ..., n]的数组中n - 1 = (2 - 1) + (3 - 2) + ... + (n - (n -1))
  2. 求最大利润时,我们把每一个都 相减 ,为 负数 时说明价格降了,那我们就不卖,即当天的交易额为0,所以Math.max(0, prices[i] - prices[i - 1])负数时取0,再将每一天的交易额 相加 ,即为最大利润
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    let ans = 0;
    let n = prices.length;
    for (let i = 1; i < n; ++i) {
        ans += Math.max(0, prices[i] - prices[i - 1]);
    }
    return ans;
};