其他分享
首页 > 其他分享> > leetcode121. 买卖股票的最佳时机

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

标签:子串,盈利,买卖,int,max,sum,leetcode121,最佳时机,prices
来源: https://www.cnblogs.com/Wade-/p/14257502.html