LeetCode--121--卖卖股票的最佳时机

问题描述:

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。

注意你不能在买入股票前卖出股票。

示例 1:

输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
     注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。

示例 2:

输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。

times out:

 1 class Solution(object):
 2     def maxProfit(self, prices):
 3         """
 4         :type prices: List[int]
 5         :rtype: int
 6         """
 7         if len(prices) == 0 or len(prices) == 1:
 8             return 0
 9         prices = prices[::-1]
10         max = prices[0] - prices[1]
11         for i in range(len(prices) -1):
12             for j in range(i + 1,len(prices)):
13                 if max <= prices[i] - prices[j]:
14                     max = prices[i] - prices[j]
15         if max < 0:
16             max = 0
17         return max

方法1:pre保存遍历过的数值的最小值,用min(pre,prices[i])对pre进行更新,用当前值prices[i]减去pre得到利润ans,用max(ans,prices[i] - pre)更新ans,return ans.

 1 class Solution(object):
 2     def maxProfit(self, prices):
 3         """
 4         :type prices: List[int]
 5         :rtype: int
 6         """
 7         if not prices:
 8             return 0
 9         ans = 0
10         pre = prices[0]
11         for i in range(1, len(prices)):
12             pre = min(pre, prices[i])
13             ans = max(prices[i] - pre, ans)
14         return ans

官方:

 1 class Solution(object):
 2     def maxProfit(self, prices):
 3         """
 4         :type prices: List[int]
 5         :rtype: int
 6         """
 7         if prices == []:
 8             return 0
 9         min_val = prices[0]
10         max_res = 0
11         for i in prices[1:]:
12             if i < min_val:
13                 min_val = i
14             max_res = max(max_res,i-min_val)
15         return max_res

2018-09-11 20:56:57

 以前写的不想看了。。。。。

 1 import sys
 2 class Solution:
 3     def maxProfit(self, prices):
 4         minPrice = sys.maxsize
 5         maxP = 0
 6         for i in range(len(prices)):
 7             if prices[i]<minPrice:
 8                 minPrice=prices[i]
 9             elif prices[i]-minPrice > maxP:
10                 maxP = prices[i]-minPrice
11         return maxP

2020-01-17 16:52:57

posted @ 2018-09-11 20:57  Assange  阅读(192)  评论(0编辑  收藏  举报