MEDIUM NC#122 Blind #5 Arrays & Hashing / Dynamic Programming (Kadane's Algorithm)

53. Maximum Subarray

šŸ“– Problem

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

🧠 Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • •Array methods (`push`, `pop`, `shift`, `slice`)
  • •Object/Map/Set usage patterns
  • •Function parameter and return typing
  • •Midpoint overflow-safe math
  • •Loop invariants
  • •Monotonic condition design

Logical Thinking Concepts

  • •Define invariants before coding
  • •Check edge cases first (`[]`, single element, duplicates)
  • •Estimate time/space before implementation
  • •Apply Binary Search reasoning pattern
  • •Apply Dynamic Programming reasoning pattern
  • •Apply Prefix Sum reasoning pattern

šŸ’” Approach

  • → Use Kadane's algorithm to track maximum sum ending at each position
  • → At each index, decide whether to extend the previous subarray or start fresh
  • → Keep track of the global maximum sum seen so far
  • → Time: O(n), Space: O(1)

šŸ› ļø Hints & Pitfalls

Hints

  • •Use Kadane's algorithm to track maximum sum ending at each position
  • •At each index, decide whether to extend the previous subarray or start fresh
  • •Keep track of the global maximum sum seen so far

Common Pitfalls

  • •Time: O(n), Space: O(1)

🧪 Test Cases

Hidden tests on submit: 3

Test Case 1
Not run
Input:
maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]);
Expected:
6
Test Case 2
Not run
Input:
maxSubArray([1, 2, 3, 4, 5]);
Expected:
15
Test Case 3
Not run
Input:
maxSubArray([-1, -2, -3, -4]);
Expected:
-1

šŸ“ Code Editor

šŸ“š Reference Solution

ā–¼
⌘K Search āŒ˜ā†© Run ⌘S Submit