当前位置 博文首页 > 文章内容

    0121. Best Time to Buy and Sell Stock (E)

    作者: 栏目:未分类 时间:2020-09-18 17:01:00

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!



    Best Time to Buy and Sell Stock (E)

    题目

    Say you have an array for which the \(i^{th}\) element is the price of a given stock on day i.

    If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

    Note that you cannot sell a stock before you buy one.

    Example 1:

    Input: [7,1,5,3,6,4]
    Output: 5
    Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
                 Not 7-1 = 6, as selling price needs to be larger than buying price.
    

    Example 2:

    Input: [7,6,4,3,1]
    Output: 0
    Explanation: In this case, no transaction is done, i.e. max profit = 0.
    

    题意

    找到数组中两个数的最大差,注意较小数需要排在较大数之前。

    思路

    使用类似动态规划的方法:从左向右遍历数组,记录leftMin为以当前下标为右边界的左子数组中的最小值,每次判断更新leftMin,并判断当前值减去leftMin是否大于最大利润,是则更新最大利润。与动态规划的区别在于不需要另开数组记录每一个下标对应的leftMin。


    代码实现

    Java

    class Solution {
        public int maxProfit(int[] prices) {
            if (prices.length == 0) {
                return 0;
            }
    
            int leftMin = prices[0];
            int maxProfit = 0;
            for (int i = 1; i < prices.length; i++) {
                if (prices[i] < leftMin) {
                    leftMin = prices[i];
                } else if (prices[i] - leftMin > maxProfit) {
                    maxProfit = prices[i] - leftMin;
                }
            }
            return maxProfit;
        }
    }
    

    JavaScript

    /**
     * @param {number[]} prices
     * @return {number}
     */
    var maxProfit = function (prices) {
      let leftMin = prices[0]
      let maxProfit = 0
      for (let i = 1; i < prices.length; i++) {
        maxProfit = Math.max(maxProfit, prices[i] - leftMin)
        leftMin = Math.min(leftMin, prices[i])
      }
      return maxProfit
    }