Skip to main content

0053 Maximum Subarray

Solved at: 2022-09-05

Questionโ€‹

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

A subarray is a contiguous part of an array.

Solutionโ€‹

class Solution:
def maxSubArray(self, nums: List[int]) -> int:
current = 0
largest = -inf
for i in nums:
current += i
if current > largest:
largest = current
if current < 0:
current = 0
return largest
  • try to see if keeping the previous "part" is worth it.
  • if it is worth it, that means the part before is positive.

Resultsโ€‹

Runtimeโ€‹

  • 1192 ms, faster than 42.26% of Python3 online submissions for Maximum Subarray.

Memory Usageโ€‹

  • 27.7 MB, less than 97.93% of Python3 online submissions for Maximum Subarray.

Complexity Analysisโ€‹

Timeโ€‹

O(N)O(N)

Spaceโ€‹

O(1)O(1)

Other Answers Onlineโ€‹

  • Divide and Conquer