leetcode53:最大子序和

思想:

1.从nums中依次取i+1个元素且对i+1个元素求和,将求和结果通过append函数放入列表count,当依次取后将count的中最大的和赋值给maxcount,然后i++,重复步骤1

2.最终返回maxcount中的最大值

class Solution:
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        maxcount = []
        for i in range(0, len(nums)):
            count = []
            for j in range(0, len(nums)-i):
                count.append(sum(nums[j:i+1+j]))
            maxcount.append(max(count))
        return max(maxcount)



if __name__ == "__main__":
    print(Solution().maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]))

小菜鸟的思想通过了198个测试案列,还有一些没能通过,说超过时间啦。后来看了大神的思想,我这个确实重复做了好多东西,以后渐渐改进

class Solution:
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 0:
            return 0
        preSum = maxSum = nums[0]
        for i in range(1, len(nums)):
            preSum = max(preSum + nums[i], nums[i])
            maxSum = max(maxSum, preSum)
        return maxSum

大佬的思想,看了好久还是半懂状态中哈哈哈哈哈哈(有机会好好拜读)

猜你喜欢

转载自blog.csdn.net/weixin_43160613/article/details/83023489
今日推荐