leetcode(45)-买卖股票的最佳时机
- 买卖股票的最佳时机
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。
注意:你不能在买入股票前卖出股票。
示例 1:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
我的思路,左边维系最小,右边维系最大,,实际上右边不需要维系最大,
右边每个元素都有它登场的时机,不必让它提前登场
class Solution:
def maxProfit(self, prices: List[int]) -> int:
ln = len(prices)
if ln<=1:return 0
min_ = prices[0]
indexs = [prices[-1] for i in range(ln)]
for i in range(0,ln-2):
indexs[ln-2-i] = max(indexs[ln-1-i],prices[ln-i-2])
max_ = prices[1]
money = max(0,max_-min_)
#print(indexs)
for i in range(1,ln-1):
##print(max_,min_)
if prices[i]<min_:
min_ = prices[i]
if prices[i]== max_:
max_ = indexs[i+1]
money = max(max_-min_,money)
return money
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) == 1 or len(prices) == 0:
return 0
low, high = prices[0], 0
for p in range(1, len(prices)):
if prices[p] < low:
low = prices[p]
if prices[p]-low >= high:
high = prices[p]-low
return high

浙公网安备 33010602011771号