LeetCode121买卖股票的最佳时机
未经博主同意,禁止瞎JB转载。
https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/description/
我的解法:
对list中的元素作一阶差分,然后本题目就转换为子序列的最大和问题的变体。
1 class Solution(object): 2 def maxProfit(self, prices): 3 """ 4 :type prices: List[int] 5 :rtype: int 6 """ 7 n = len(prices) 8 if n < 2: 9 return 0 10 diff = [prices[i+1] - prices[i] for i in range(n-1)] 11 maxer = 0 12 maxset = [] 13 for j in range(n-1): 14 maxer = max(0,maxer + diff[j]) 15 maxset.append(maxer) 16 return max(maxset)
原文:https://www.cnblogs.com/kianqunki/p/9846002.html