算法:买卖股票的最佳时机(快慢指针和动态规划)

算法:买卖股票的最佳时机(快慢指针和动态规划)_第1张图片

快慢指针 时间复杂度 O(n) 空间复杂度 O(1)

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function (prices) {
    let l = 0
    let r = 1
    let temp = 0
    while (r <= prices.length - 1) {
        // 如果当前左值大于右值说明当前不是最佳买入时机
        // 所以将右指针赋值给左指针并将右指针向右移动
        if (prices[l] > prices[r]) {
            l = r
            r++
        } else {
            // 如果左值小于右值先判断当前最大利润是否大于之前的利润
            // 大于则替换
            // 将右指针向右移动
            if (prices[r] - prices[l] > temp) {
                temp = prices[r] - prices[l]
            }
            r++
        }
    }
    return temp
};

动态规划 时间复杂度 O(n) 空间复杂度 O(1)

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function (prices) {
   // 将数组中最大的值设置为最小的买入值
   let minCost = Math.max(...prices)
   let profit = 0
   for(let item of prices){
       // 更新最小的买入值
       minCost = Math.min(item,minCost)
       // 更新最大利润
       profit = Math.max(profit,item-minCost)
   }
   return profit
};

你可能感兴趣的:(算法,动态规划,算法)