26. Maximum Subarray
mediumAsked at PostmanFind the contiguous subarray with the largest sum.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Constraints
1 <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4
Examples
Example 1
nums = [-2,1,-3,4,-1,2,1,-5,4]6Example 2
nums = [1]1Approaches
1. Prefix sum O(n^2)
Use prefix sums; for each (i, j) compute sum[j] - sum[i-1] and track the max.
- Time
- O(n^2)
- Space
- O(n)
// build prefix; double loop over (i, j)Tradeoff:
2. Kadane
Maintain best-ending-here = max(num, best-ending-here + num); the global best is the max over those values.
- Time
- O(n)
- Space
- O(1)
function maxSub(nums) {
let curr = nums[0], best = nums[0];
for (let i = 1; i < nums.length; i++) {
curr = Math.max(nums[i], curr + nums[i]);
best = Math.max(best, curr);
}
return best;
}Tradeoff:
Postman-specific tips
Postman values Kadane verbalized as an online algorithm — request-latency rolling windows in their monitor stream use the same single-pass extend-or-restart pattern.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Maximum Subarray and other Postman interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →