leetcode121 买卖股票的最佳时机

67 阅读1分钟

121. 买卖股票的最佳时机 - 力扣(LeetCode)

思路:一次买入卖出,无手续费用。

双层循环:超时

    let max = 0
    let len = prices.length
    for (let i = 0; i < len; i++) {
        for (let j = i + 1; j < len; j++) {
            if (prices[j] > prices[i]) {
                max = Math.max(max, prices[j] - prices[i])
            }
        }
    }
    return max

动态规划

    let min = Infinity
    let max = 0
    //获取当前元素前面的最小值 
    for (let val of prices) {
        max = Math.max(max, val - min)
        min = Math.min(min, val)
    }
    return max

双指针:右指针用来进行从头到尾的循环,左指针什么时候移动,因为左指针指向的是右指针左边元素中的最小值,所以当有元素比左指针小的时候会进行移动。

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function (prices) {
    let left = 0, right = 0
    let len = prices.length
    let max = 0
    while (right < len) {
        if (prices[left] > prices[right]) {
            left = right
        }
        max = Math.max(max, prices[right] - prices[left])
        right++
    }
    return max
};
let prices = [7, 1, 5, 3, 6, 4]
// prices = [7, 6, 4, 3, 1]
console.log(maxProfit(prices))

dp处理留坑。。。