码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 53. Maximum Subarray

时间:2020-05-18 22:47:34      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:lin   inline   sub   glob   not   tput   divide   str   self   

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

标签:lin   inline   sub   glob   not   tput   divide   str   self   

原文地址:https://www.cnblogs.com/arcsinw/p/12913102.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!