- 题目描述
给定一个数组,它的第 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。
- 解决思路一
暴力法,时间复杂度为O(N^2),但是超时了,所以没有通过。
- 代码一
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
maxprofit = 0
for i in range(len(prices)):
for j in range(i+1,len(prices)):
profit = prices[j]- prices[i]
if profit > maxprofit:
maxprofit = profit
return maxprofit
- 解决思路二
参照网上的思路:在价格最低的时候买入,差价最大的时候卖出。用一个变量来保存最低价,另一个变量来保存差价的最大值。一次循环就能够完成这两个值的查找和更新。
- 代码二
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) < 2:
return 0
profit = 0
#找出最低价时买入
minimum = prices[0]
for i in prices:
#找出买入的最佳时机:最低价
minimum = min(i, minimum)
#找出卖出的最佳时机:最高价-最低价的最大值
profit = max(i - minimum, profit)
return profit