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

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

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

class Solution:
    def FindGreatestSumOfSubArray(self, array: List[int]) -> List[int]:
        # First: find the best value
        best = array[0]
        sum_cum = 0
        for i in range(len(array)):
            sum_cum = max(sum_cum + array[i], array[i])
            best = max(best, sum_cum)
        # Then, find the best solution
        sum_cum = 0
        start_idx, end_idx = 0, 0
        solutions = {}
        for i in range(len(array)):
            if sum_cum + array[i] >= array[i]:
                sum_cum = sum_cum + array[i]
                end_idx = i
                if sum_cum == best:
                    solutions[(start_idx, end_idx)] = end_idx - start_idx + 1
            else:
                sum_cum = array[i]
                start_idx, end_idx = i, i
                if len(solutions) == 0 and sum_cum == best:
                    solutions[(start_idx, end_idx)] = end_idx - start_idx + 1
        start_idx, end_idx = max(solutions, key=solutions.get)
        return array[start_idx:end_idx+1]

解题思路:

首先找到最优的值 best,参考 连续子数组的最大和

第二步开始寻找满足最优值的所有解,存储在字典 solutions 中(键:最优解第一个元素和最后一个元素的下标的元组 (start_idx, end_idx);值:最优解的长度)

每当当前的 sum_cum 等于 best 时,就存储 (start_idx, end_idx);

注意:由于要找长度最长的的最优解(且这个解唯一),所以如果字典 solutions 中已经非空,并且 start_idx 等于 end_idx,此时可以不存储这个长度为 1 的解

全部评论

相关推荐

07-10 14:08
已编辑
江西农业大学 Java
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 12:04
毕业生招你惹你了,问一个发薪日来一句别看网上乱七八糟的你看哪个工作没有固定发薪日扭头就取消了面试就问了一句公司都是这个态度吗还搞上人身攻击了...
程序员小白条:呃呃呃,都还没面试,我都不会问这么细,何况通不通过,去不去都另说,你没实力和学历的话,在外面就这样,说实话没直接已读不回就不错了,浪费时间基本上
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务