剑指Offer(Python多种思路实现):连续子数组的最大和

面试42题:

题目:连续子数组的最大和

题:输入一个整形数组,数组里有正数也有负数。数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。要求时间复杂度为O(n)

解题思路一:在数组里从前向后遍历,记录下每次的“当前累加子数组和”和“当前的最大子数组和”

class Solution:
    g_InvalidInput=False
    def FindGreatestSumOfSubArray(self, array):
        # write code here
        if not array or len(array)<=0:
            g_InvalidInput=True
            return 0
        
        g_InvalidInput=False
        curSum=0
        greatSum=float('-inf')
        for i in array:
            if curSum<=0:
                curSum=i
            else:
                curSum+=i
            if curSum>greatSum:
                greatSum=curSum
        return greatSum

解题思路二:

def maxSubArray(self, nums):
    from itertools import accumulate
    return max(accumulate(nums, lambda x, y: x+y if x > 0 else y))
发布了53 篇原创文章 · 获赞 3 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44151089/article/details/104489876
今日推荐