leetcode121. 买卖股票的最佳时机

题目链接

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
posted @ 2021-01-10 10:24  deepwzh  阅读(61)  评论(0编辑  收藏  举报