小白js硬啃leetcode算法-买卖股票的最佳时机(数组简单-121)-3

105 阅读1分钟

题目

53、给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和 你可以按任意顺序返回答案

范例: 输入:[7,1,5,3,6,4]
输出:5
解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。

暴力解法

  • 解题思路:
    • 本题可以直接双层循环,依次求出买卖利润,之后进行比较即可得到最大利润
  • 复杂度
    • 时间复杂度:O(n^2)
    • 空间复杂度: O(1)
const maxProfit = function(prices) {
    let mProfit = 0
    for( let i =0; i< prices.length; i++  ){
        for( let j = i+1; j< prices.length; j++ ){
            mProfit = (prices[j]-prices[i]) >  mProfit ? prices[j]-prices[i]:mProfit
        }
    }
    return mProfit
};

循环一次求解

  • 解题思路:
    • 股票买卖应为只能先买再卖,所以利润的买入价必在卖出价之前,由此可以知道我们先取低价,再取高价,相差的利润
  • 复杂度
    • 时间复杂度:O(n)
    • 空间复杂度: O(1)
const maxProfit = function(prices) {
    let minPrice = prices[0]
    let mProfit = 0
    prices.forEach(p=>{
        mProfit = mProfit > (p-minPrice)? mProfit:p-minPrice
        if( minPrice > p ){
            minPrice = p
        }
    })
    return mProfit
};

题目来源:力扣(LeetCode)
链接:leetcode-cn.com/problems/ma…