题目
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: 0
In this case, no transaction is done, i.e. max profit = 0.
题意
好吧,这道题我一开始也没看懂题意,在discuss版块看到一楼主的解释贴才明白的,重点就在stock,意思是股票。然后这道题就是说给你这段时间的股价,然后你选择一天买入一天卖出,要求收益最高。
大家应该一下子 就明白了,然后解法也是很直接的,只要注意到买的时间一定是要先于卖的时间。如果从数据上说就是极小值要先于极大值,那其实就是相当于求分成一段段的极小值统治的区间,每个区间的开始肯定就是这个区间的极小值,然后去看极小值和区间所在的极大值的数据大小差。可以体会一下,然后实现比说的简单多了,就是去持有一个极小值然后让它去减后续比它大的数,直到遇到另外一个更小的极小值,由这个极小值更替当前极小值进行后续更新。至于为什么不能直接找最大值和最小值直接相减,样例里面也给出了,就是这个顺序的问题。
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
minus = 0
min_prices = 2147483647
for i in range(len(prices)):
if prices[i] < min_prices:
min_prices = prices[i]
else:
if minus < prices[i] - min_prices:
minus = prices[i] - min_prices
return minus