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.
分析:这个题目看着简单,但是有个陷阱。 一开始我想的太简单,直接max -min不就结了。但是max值可能出现在min值之后,还没买,怎么卖?这里讨论的是传统股票,必须先买再卖那种。 后来参考别人的写法,扫描一遍,不停的更新最小值,然后按时间顺序出现的current price与min price的差值,更新最大值。
class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
if not prices: return 0 # prices is empty
maxProfit = 0
minPrice = prices[0]
for currPrice in prices:
minPrice = min(minPrice, currPrice)
maxProfit = max(maxProfit, currPrice - minPrice)
return maxProfit