题解 | #连续子数组的最大和(二)#

连续子数组的最大和(二)

https://www.nowcoder.com/practice/11662ff51a714bbd8de809a89c481e21

class Solution:
    def FindGreatestSumOfSubArray(self, array: List[int]) -> List[int]:
        # write code here
        dp = [0 for i in range(len(array))]
        dp[0] = array[0]
        maxsum = dp[0]
        # 滑动区间
        left = 0
        right = 0
        # 记录最长的区间
        resl = 0
        resr = 0
        for i in range(1,len(array)):
            if dp[i-1]+array[i]>=array[i]:
                dp[i] = dp[i-1]+array[i]
                right = i
                thissum = dp[i]
                if thissum>=maxsum:
                    maxsum = thissum
                    if right-left>resr-resl:
                        resl = left
                        resr = right
            else:
                dp[i] = array[i]
                left = i
                right = i
                thissum = dp[i]
                if thissum>maxsum:
                    maxsum = thissum
                    resl = left
                    resr = right
                elif thissum==maxsum:
                    if right-left>resr-resl:
                        resl = left
                        resr = right
        
        return array[resl:resr+1]

全部评论

相关推荐

02-28 17:01
门头沟学院 C++
俊朗的铁猫希望被捞:兄弟如果只想搞钱的话,你这个简历最适合的其实是辅导机构做dai写啥的真的特别赚
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务