• leetcode-121-Best Time to Buy and Sell Stock


    题目描述:

    Say you have an array for which the ith 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.
    

     

    要完成的函数:

    int maxProfit(vector<int> &prices)

     

    说明:

    1、给定一个vector,第几个元素表示某只股票第几天的价格,你只能买卖一次,要求输出最大的盈利额,你只能先买再卖。

    2、这道题目其实是找出最大的差值,最暴力的解法无非是双重循环,外重循环找到每次“低峰值”,内重循环在“低峰值”之后计算差值,存储最大的差值。

    但是上述做法你会发现没有必要找到每一个低峰值,因为第二次低峰值如果大于第一次低峰值,那么就没有必要做下去了;如果小于第一次低峰值,那么前面的内重循环到第二次低峰值就该停下来了。

    我们需要的只是比第一个低峰值更小的另一个低峰值。

    所以这道题目我们其实可以只用一次遍历就实现出来,不断更新低峰值,不断更新最大差值。

    代码如下:

        int maxProfit(vector<int> &prices) 
        {
            int res=0;
            int minprice=INT_MAX;
            for(int i=0;i<prices.size();i++)
            {
                minprice= min(minprice, prices[i]);//不断更新低峰值
                res=max(res,prices[i]-minprice);//不断更新最大差值
            }
            return res;
        }
    

    上述代码实测8ms,beats 80.63% of cpp submissions。

  • 相关阅读:
    ▶ 0001 No application 'E:wwwgolog' found in your GOPATH
    beego路由
    go sync.WaitGroup
    idea修改filetype
    deepin添加设置快捷键
    mysql数据库被攻击
    linux桌面系统的约定
    deepin把vscode设为默认文本应用
    linux应用管理
    当你在工作中失去动力时该怎么办?
  • 原文地址:https://www.cnblogs.com/chenjx85/p/9104432.html
Copyright © 2020-2023  润新知