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

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

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 的解

全部评论

相关推荐

03-16 22:00
武汉大学 C++
幸福的小熊猫想要offer:我阿里投的 c++岗,面试官说自己是做 java 的,c++这辈子才有了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务