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

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

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]

全部评论

相关推荐

11-02 09:49
已编辑
货拉拉_测试(实习员工)
热爱生活的仰泳鲈鱼求你们别卷了:没事楼主,有反转查看图片
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务