24.leetcode121_best_time_to_buy_and_sell_stock
1.题目描述
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.
现在有一股股票第i天的市价,选择好日子买完再卖出去(为了获得最大利润)。
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.
2.题目分析
题目给出的条件是买一股求最大利润,所以求max(a[i]-a[k])(0=<k<i<len(prices)),如果这个最大值比0小的话,就不买了。这个题与53题类似,都是要用“线性时间算法”,一次遍历后得到结果。
3.解题思路
1 class Solution(object): 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 #返回0 10 min=prices[0] #假设第一天是是最低的 11 max_sum=0 #假设最大值为0 12 i=0 13 while i<n: 14 if prices[i]-min<=0: #如果当前价格小于min 15 min=prices[i] #最小为princes[i] 16 tempmax=0 #临时最大利润变为0 17 else: 18 tempmax=max(tempmax,prices[i]-min) #获取临时最大利润 19 max_sum=max(tempmax,max_sum) #获取总最大利润 20 i+=1 21 if max_sum<=0: #最大利润小于等于0 22 return 0 #返回0 23 else: 24 return max_sum #返回最大利润