leetcode(121). Best Time to Buy and Sell Stock
来源:互联网 发布:淘宝审核原图的标准 编辑:程序博客网 时间:2024/06/10 09:00
problem
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 (ie,
buy one and sell one share of the stock), design an algorithm to find
the maximum profit.Example 1: Input: [7, 1, 5, 3, 6, 4] Output: 5
max. difference = 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: 0In this case, no transaction is done, i.e. max profit = 0.
分析
In formal terms, we need to find
接下来再进一步抽象这个问题:对每一个元素都减去它之前最小的元素,这样得到的最大值就是要求的结果,
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ minprice = float('inf') ans = 0 for i in prices: if i < minprice: minprice = i else: ans = max(ans, i-minprice) return ans
- 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
- LeetCode: Best Time to Buy and Sell Stock [121]
- LeetCode 121 Best Time to Buy and Sell Stock
- [leetcode 121] Best Time to Buy and Sell Stock
- Leetcode NO.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 (Java)
- leetcode-121 Best Time to Buy and Sell Stock
- leetcode || 121、Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock - LeetCode 121
- 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
- leetcode 121: Best Time to Buy and Sell Stock
- leetcode: (121) Best Time to Buy and Sell Stock
- 121 Best Time to Buy and Sell Stock [Leetcode]
- 浅谈Android事件分发机制
- SpringMVC学习系列(4) 之 数据绑定-1
- Java 多线程-java.util.concurrent锁对象
- D.6三角公式求值
- 8.6 A
- leetcode(121). Best Time to Buy and Sell Stock
- mxgraph 搭建简单应用 主线描述、属性与方法的意思
- python 生成200个激活码并存进数据库
- ZCMU 1721: on xh kd lh (凯撒密码,水)
- java.lang.ClassNotFoundException: com.mysql.jdbc.Driver问题
- 字符序列反转的几种算法
- 51nod 1278 相离的圆
- Python机器学习及实践——简介篇3(结合例子)
- 时间复杂度为O(n)的排序