前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode-121-Best Time to Buy and Sell Stock

leetcode-121-Best Time to Buy and Sell Stock

作者头像
chenjx85
发布2019-03-21 16:28:11
3100
发布2019-03-21 16:28:11
举报

题目描述:

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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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、这道题目其实是找出最大的差值,最暴力的解法无非是双重循环,外重循环找到每次“低峰值”,内重循环在“低峰值”之后计算差值,存储最大的差值。

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

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

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

代码如下:

代码语言:javascript
复制
    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。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-05-29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述:
  • 要完成的函数:
  • 说明:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档