美文网首页
连续子数组的最大和

连续子数组的最大和

作者: momo1023 | 来源:发表于2019-03-27 22:20 被阅读0次
    1. 不需要输出子数组
    # -*- coding:utf-8 -*-
    class Solution:
        def FindGreatestSumOfSubArray(self, array):
            # write code here
            sums = 0
            max_sum = array[0]
            
            for i in range(len(array)):
                sums += array[i]
                if sums > max_sum:
                    max_sum = sums
                if sums < 0:
                    sums = 0
            return max_sum
    
    1. 需要输出子数组
    # -*- coding:utf-8 -*-
    class Solution:
        def FindGreatestSumOfSubArray(self, array):
            # write code here
            sums = 0
            max_sum = array[0]
            start = 0
            l = 0
            r = 0
            for i in range(len(array)):
                sums += array[i]
                if sums > max_sum:
                    max_sum = sums
                    l = start
                    r = i
                if sums < 0:
                    sums = 0
                    start = i + 1
            res = 0
            for num in array[l:r+1]:
                res += num
            return res
    

    相关文章

      网友评论

          本文标题:连续子数组的最大和

          本文链接:https://www.haomeiwen.com/subject/mujxbqtx.html