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.
暴力超时:
1 class Solution: 2 def maxProfit(self, prices): 3 """ 4 :type prices: List[int] 5 :rtype: int 6 """ 7 n = len(prices) 8 if n==0: 9 return 0 10 max_diff = 0 11 for i in range(n): 12 for j in range(i,n): 13 diff = prices[j]-prices[i] 14 if diff>max_diff: 15 max_diff = diff 16 17 return max_diff 18 19
只需要找出最大的差值即可,即 max(prices[j] – prices[i]) ,i < j。一次遍历即可,在遍历的时间用遍历low记录 prices[o….i] 中的最小值,就是当前为止的最低售价,时间复杂度为 O(n)。
class Solution: def maxProfit(self, a): """ :type prices: List[int] :rtype: int """ n = len(a) if n==0: return 0 mins = a[0] max_diff = 0 for i in range(1,n): #买入价也可以看成是卖出价 #找到到截止到第i天的最低买入价 if(a[i]<mins): mins = a[i] # 更新最大收益 elif max_diff < a[i] - mins: max_diff = a[i] - mins return max_diff