121. Best Time to Buy and Sell Stock [easy] (Python)
2016-05-28 01:02
573 查看
题目链接
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/题目原文
Say you have an array for which the ithi^{th} element is the price of a given stock on day ii.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天的股票价格。如果你最多只能进行一次买卖操作(买一次,卖一次),设计一个算法求出最大的收益。思路方法
直观的理解,就是求数组中 max(array[j]-array[i]), j>=i。用两重循环求出每一对不同i,j的差值,这样做会超时,所以要用更巧妙的方法。思路一
实际上,一次循环就可以求出结果。在遍历的过程中,用一个变量保存目前为止最小的数,用当前的数与目前最小的数相减,判断这个差与此前得到的最大收益的大小,取较大值更新最大收益。代码
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if len(prices) == 0: return 0 minPrice = prices[0] maxProfit = 0 for p in prices: if p < minPrice: minPrice = p elif p - minPrice > maxProfit: maxProfit = p - minPrice return maxProfit
思路二
实际上,这道题本质上是个动态规划问题。如果上面的代码不太好理解,可以尝试理解下面的代码。代码
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if len(prices) == 0: return 0 minPrice = prices[0] dp = [0] * len(prices) for i in xrange(0, len(prices)): dp[i] = max(dp[i-1], prices[i] - minPrice) minPrice = min(minPrice, prices[i]) return dp[-1]
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:/article/11857842.html
相关文章推荐
- 线性回归总结及python实现
- python自动翻译实现方法
- Python的几个高级语法概念浅析(lambda表达式闭包装饰器)
- Python - 数字转换字符串
- 安装Python管理包pip,并利用pip安装 scrapy框架
- python调用php函数
- mac下的应用程序发布 及 打包(Python写的脚本,可打包第三方库)
- python 练习 28
- python 练习 29
- python 练习 30
- Python 练习 31
- python 练习 26
- python 练习 25
- python 练习24
- python 练习 23
- python 练习 22
- python 练习 27
- 数塔python
- python_day3学习笔记
- Python小脚本—批量修改文件名与文件扩展名升级版