Skip to main content

13. Maximum Subarray

easyAsked at Grab

Find the contiguous subarray with the largest sum — Grab uses this as a Kadane's algorithm fluency check.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

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

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4

Examples

Example 1

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

Example 2

Input
nums = [1]
Output
1

Approaches

1. Brute force O(n^2)

Test every starting index and accumulate sums.

Time
O(n^2)
Space
O(1)
let best = -Infinity;
for (let i = 0; i < n; i++) {
  let sum = 0;
  for (let j = i; j < n; j++) {
    sum += nums[j];
    best = Math.max(best, sum);
  }
}

Tradeoff:

2. Kadane's algorithm

Track running max ending at each index — reset to current element if running sum drops below it.

Time
O(n)
Space
O(1)
function maxSubArray(nums) {
  let cur = nums[0], best = nums[0];
  for (let i = 1; i < nums.length; i++) {
    cur = Math.max(nums[i], cur + nums[i]);
    best = Math.max(best, cur);
  }
  return best;
}

Tradeoff:

Grab-specific tips

Grab interviewers expect Kadane's in the first 5 minutes — frame as peak earnings window across a driver shift on the SEA super-app.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Maximum Subarray and other Grab interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →