题意:给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。注意你不能在买入股票前卖出股票。
分析:求区间内的差值最大,结合53题最大子序和,构建一个前后差的数组,然后求数组区间内的最大和。即为最大利益。
可以理解为题目要求最大价格差,我们可以构造一个数组,prices[i]-prices[i-1],代表每日能获得的利润值,这个数组的最大连续子数组和就是最大利润,即最大价格差。
动态规划
class Solution:
def maxProfit(self, prices) -> int:
if len(prices)<=1:
return 0
nums=[1]*(len(prices)-1)
for i in range(1,len(prices)):
nums[i-1]=prices[i]-prices[i-1]#制造差值数组,以下为求差值数组的最大子序和。
max_sum = nums[0]
for i in range(1,len(nums)):
if nums[i-1]>0:
nums[i] +=nums[i-1]
max_sum = max(nums[i],max_sum)
return max(max_sum,0)
例如:[7,4,2,1]因为股票可以一直不买,即为0,而不是返回负数。所以和53题最大子序和还不一样,最后加入max(max_sum,0),即使都是负数,也返回0
时间复杂度为O(N),空间复杂度O(N)
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) <= 1:
return 0
prev = prices[0]
max_profit = 0
max_here = 0
for t in prices[1:]:
x = t - prev
prev = t
max_here = max_here + x if max_here > 0 else x
max_profit = max(max_profit, max_here)
return max_profit
时间复杂度O(N),空间复杂度O(1)