[LeetCode]题解(python):121-Best Time to Buy and Sell Stock

题目来源:

  https://leetcode.com/problems/best-time-to-buy-and-sell-stock/


题意分析:

  给定一个数组,代表array[i] 代表第i天的价格。问买买卖这个物品一次的最高利润是多少(i买,j卖,j > i)。


题目思路:

  记录当前最小值,如果array[i] < min,那么更新min,否者计算如果在i天的卖的利润,和当前最大利润比较。


代码(python):

  

 1 class Solution(object):
 2     def maxProfit(self, prices):
 3         """
 4         :type prices: List[int]
 5         :rtype: int
 6         """
 7         if len(prices) == 0:
 8             return 0
 9         ans,mins = 0,prices[0]
10         for i in prices:
11             if i > mins:
12                 ans = max(ans,i - mins)
13             else:
14                 mins = i
15         return ans
View Code
原文地址:https://www.cnblogs.com/chruny/p/5302496.html