版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014256231/article/details/83502713
题目:
给定一个数组,它的第 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。
我的解法1: 把所有可能的差找到,再求max,超时了
class Solution(object):
def maxProfit(self, prices):
if len(prices) == 0 or len(prices) == 1:
return 0
mi = []
for i in range(len(prices)-1):
for j in range(i+1, len(prices)):
mi.append(prices[j] - prices[i])
maxmi = max(mi) if max(mi)> 0 else 0
return maxmi
我的解法2: 从后向前遍历一次,维护两个变量,到目前为止的最大值和比最大值小的值,maxnum 和 minnum,每次有个minnum就计算一下差值,维护一个存最大差值的变量_max,保存一下差值最大值。
class Solution(object):
def maxProfit(self, prices):
if len(prices) == 0:
return 0
maxnum = prices[-1]
minnum = prices[-1]
_max = 0
for i in range(len(prices)-1,0,-1):
if prices[i-1] > maxnum:
maxnum = prices[i-1]
if prices[i-1] < maxnum:
minnum = prices[i-1]
_max = max(_max, maxnum - minnum)
return _max
我的解法3:正向遍历一次,维护两个变量: minnum和maxprofit。要找的是每个最小值之后的最大差值
class Solution(object):
def maxProfit(self, prices):
if len(prices) == 0:
return 0
maxprofit = 0
minnum = prices[0]
for i in range(1, len(prices)):
if prices[i] < minnum:
minnum = prices[i]
else:
maxprofit = max(maxprofit, prices[i]-minnum)
return maxprofit