Top 150 InterviewHard

Maximum Subarray

Detailed guide and Python implementation for the 'Maximum Subarray' problem.

Problem Statement

Hard

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

Write a function maxSubArray(nums: List[int]) -> int.

Constraints
  • 1 <= len(nums) <= 10^5
  • -10^4 <= nums[i] <= 10^4

Examples

Example 1
Input
nums = [-2,1,-3,4,-1,2,1,-5,4]
Output
6
Explanation

[4,-1,2,1] has the largest sum = 6.

Example 2
Input
nums = [1]
Output
1
Explanation

[1] has the largest sum = 1.

Need a Hint?
Consider using Greedy-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.