博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode-121-Best Time to Buy and Sell Stock
阅读量:7022 次
发布时间:2019-06-28

本文共 1179 字,大约阅读时间需要 3 分钟。

题目描述:

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: 5Explanation: 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: 0Explanation: In this case, no transaction is done, i.e. max profit = 0.

 

要完成的函数:

int maxProfit(vector<int> &prices)

 

说明:

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

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

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

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

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

代码如下:

int maxProfit(vector
&prices) { int res=0; int minprice=INT_MAX; for(int i=0;i

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

转载于:https://www.cnblogs.com/chenjx85/p/9104432.html

你可能感兴趣的文章
Jav解析xml
查看>>
linux学习篇(一)
查看>>
Python网络数据采集PDF
查看>>
topcoder srm 662 div1
查看>>
(备忘)获取调用者类名的一种方法
查看>>
26. Remove Duplicates from Sorted Array(代码思路新奇)
查看>>
思维体操: HDU1287破译密码
查看>>
How To Partition Existing Table Using DBMS_Redefinition
查看>>
微信“跳一跳”高分技巧
查看>>
Codeforces 855C - Helga Hufflepuff's Cup
查看>>
在线预览文件(pdf)
查看>>
Python之路----生成器函数进阶
查看>>
慢查询阻塞了xtrabackup进而阻塞以后的sql导致的系统瘫痪问题
查看>>
L148
查看>>
l366 多元化
查看>>
数据结构学习第二天
查看>>
Velocity.js的使用
查看>>
VS 2008 修改C++文件默认模板
查看>>
Java核心基础学习(一)--- 2019年1月
查看>>
ADO.NET编程之美----数据访问方式(面向连接与面向无连接)
查看>>