7. Maximum Subarray
easyAsked at SoFiFind the contiguous subarray with the largest sum — SoFi frames this as finding the best contiguous return window in a portfolio's daily PnL series.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an integer array, find the contiguous subarray with the largest sum and return that 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. Brute force
Try every (i, j) window.
- Time
- O(n^2)
- Space
- O(1)
let best = -Infinity;
for (let i = 0; i < nums.length; i++) {
let sum = 0;
for (let j = i; j < nums.length; j++) {
sum += nums[j];
best = Math.max(best, sum);
}
}Tradeoff:
2. Kadane's
Track the best subarray ending at i: either extend or restart. SoFi expects you to recognize this immediately.
- 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:
SoFi-specific tips
SoFi rewards Kadane's plus a one-line connection to scanning daily portfolio returns for the best contiguous gain window.
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 SoFi interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →