Lintcode149 Best Time to Buy and Sell Stock solution 题解
来源:互联网 发布:mysql truncate函数 编辑:程序博客网 时间:2024/06/07 06:06
【题目描述】
Say you have an array for which theithelement is the price of a given stock on dayi.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。
【题目链接】
www.lintcode.com/en/problem/best-time-to-buy-and-sell-stock/
【题目解析】
I限制了只能买卖一次。于是要尽可能在最低点买入最高点抛出。这里的一个隐含的限制是抛出的时间必须在买入的时间之后。所以找整个数组的最大最小值之差的方法未必有效,因为很可能最大值出现在最小值之前。但是可以利用类似思路,在扫描数组的同时来更新一个当前最小值minPrice。这样能保证当扫到i时,minPrices必然是i之前的最小值。当扫到i时:
如果prices[i] < minPrice,则更新minPrice = prices[i]。并且该天不应该卖出。
如果prices[i] >= minPrice,则该天可能是最好的卖出时间,计算prices[i] - minPrice,并与当前的单笔最大利润比较更新。
【参考答案】
www.jiuzhang.com/solutions/best-time-to-buy-and-sell-stock/
- Lintcode149 Best Time to Buy and Sell Stock solution 题解
- [LeetCode] Best Time to Buy and Sell Stock Solution
- [LeetCode] Best Time to Buy and Sell Stock II Solution
- [LeetCode] Best Time to Buy and Sell Stock III Solution
- Lintcode150 Best Time to Buy and Sell Stock II solution 题解
- Lintcode151 Best Time to Buy and Sell Stock III solution 题解
- LeetCode - Best Time to Buy and Sell Stock III 题解
- LeetCode题解-Best Time to Buy and Sell Stock
- LeetCode题解-Best Time to Buy and Sell Stock II
- LeetCode题解-Best Time to Buy and Sell Stock III
- LeetCode题解:Best Time to Buy and Sell Stock
- LeetCode题解:Best Time to Buy and Sell Stock II
- LeetCode题解:121. Best Time to Buy and Sell Stock
- Leetcode题解 121. Best Time to Buy and Sell Stock
- LeetCode 121 Best Time to Buy and Sell Stock题解
- LeetCode122. Best Time to Buy and Sell Stock II题解
- LeetCode121. Best Time to Buy and Sell Stock题解
- 【LeetCode题解】121. Best Time to Buy and Sell Stock
- 零基础学习R-加载数据包car报错
- Hadoop学习笔记(四)YARN
- PAT 1002. Business (35)
- 自己简单实现Spring的IOC原理
- python 知识小结(3)
- Lintcode149 Best Time to Buy and Sell Stock solution 题解
- maven中的scope属性
- JS实现checkbox的全选和取消全选
- AndroidStudio中使用JNI的两种方式
- 作业1013
- 6.Spark SQL:Parquet数据源之合并元数据
- jvm
- Golang: 使用flag包进行命令行参数解析
- JS实现网页时钟