Maximum Subarray - Problem

Given an integer array nums, find the subarray with the largest sum, and return its sum.

A subarray is a contiguous non-empty sequence of elements within an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
💡 Note: The subarray [4,-1,2,1] has the largest sum = 6
Example 2 — Single Element
$ Input: nums = [1]
Output: 1
💡 Note: Array has only one element, so maximum subarray sum is 1
Example 3 — All Negative
$ Input: nums = [-2,-1]
Output: -1
💡 Note: The subarray [-1] has the largest sum = -1

Constraints

  • 1 ≤ nums.length ≤ 105
  • -104 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Maximum Subarray Problem INPUT nums = [-2,1,-3,4,-1,2,1,-5,4] -2 [0] 1 [1] -3 [2] 4 [3] -1 [4] 2 [5] 1 [6] -5 [7] 4 [8] Max Subarray Array length: 9 ALGORITHM STEPS Kadane's Algorithm 1 Initialize maxSum = nums[0] = -2 currentSum = nums[0] = -2 2 Iterate Array For each element from i=1 to end of array 3 Update Current currentSum = max(nums[i], currentSum + nums[i]) 4 Update Maximum maxSum = max(maxSum, currentSum) Trace at index 6: idx: 3 4 5 6 cur: 4 3 5 6 max: 4 4 5 6 FINAL RESULT Maximum Subarray Found: 4 -1 2 1 indices [3] to [6] Sum: 4 + (-1) + 2 + 1 Output: 6 OK - Maximum sum subarray found! Time: O(n) | Space: O(1) Key Insight: Kadane's Algorithm uses dynamic programming: at each position, decide whether to extend the current subarray or start fresh. If adding the current element makes the sum worse than just the element itself, start a new subarray. Track the global maximum throughout the iteration. TutorialsPoint - Maximum Subarray | Optimal Solution (Kadane's Algorithm)
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
125.0K Views
Very High Frequency
~15 min Avg. Time
2.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen