题目链接

https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/

题解

思路

转化为最大连续子串和问题
题目要求只能卖一次,并且要让盈利最大。可以将卖一次分解为卖多次,令其每天都买入卖出,记录其盈利情况。得到盈利子串,在盈利子串中求最大连续子串和,即为最大盈利额。

代码

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        T=[]
        for i in range(1,len(prices)):
            T.append(prices[i]-prices[i-1])
        max_p=0
        sum = 0
        for i in range(len(T)):
            if sum + T[i]>=0:
                sum += T[i]
                max_p = max(max_p,sum)
            else:
                sum = 0
        return max_p

相关文章:

  • 2022-12-23
  • 2021-12-27
  • 2021-04-03
  • 2021-10-22
  • 2021-09-25
猜你喜欢
  • 2021-12-27
  • 2021-05-24
  • 2021-04-04
相关资源
相似解决方案