您的位置:首页 > 编程语言 > Python开发

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: