[LeetCode] 53. Maximum Subarray

Posted arcsinw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 53. Maximum Subarray相关的知识,希望对你有一定的参考价值。

Description

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Follow up:

If you have figured out the (O(n)) solution, try coding another solution using the divide and conquer approach, which is more subtle.

Analyse

找出一个数组连续子序列的最大和

子序列要求连续,子序列向右扩展分为两种情况

  1. 将新元素加入子序列,子序列长度+1
  2. 抛弃之前的子序列,新元素成为新的子序列,子序列长度为1

子序列的局部最大和为这两种情况中和最大的那个

在所有的局部最大和中找出全局最大和

写出一个算法复杂度为(O(n))的版本

  def maxSubArray(self, nums: List[int]) -> int:
        maximum = nums[0]
        global_maximum = nums[0]

        for i in nums[1:]:
            maximum = max(maximum + i, i)
            global_maximum = max(maximum, global_maximum)

        return global_maximum

以上是关于[LeetCode] 53. Maximum Subarray的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 53. Maximum Subarray

leetcode 53. Maximum Subarray

Leetcode 53 Maximum Subarray

41. leetcode 53. Maximum Subarray

Leetcode53 Maximum Subarray

LeetCode练题——53. Maximum Subarray