7. Maximum Subarray
easyAsked at NubankFind the largest profitable contiguous period from a daily P&L series on a credit portfolio.
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. Brute force
Try every (i,j) subarray.
- Time
- O(n^2)
- Space
- O(1)
let best=-Infinity;
for(let i=0;i<n;i++){let s=0; for(let j=i;j<n;j++){s+=nums[j]; best=Math.max(best,s);}}
return best;Tradeoff:
2. Kadane
Carry running sum; reset to nums[i] when it dips negative.
- Time
- O(n)
- Space
- O(1)
function maxSubArray(nums) {
let best = nums[0], cur = 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:
Nubank-specific tips
Nubank reviewers expect candidates to explain the negative-sum invariant out loud — they read it as a proxy for understanding monotonic accumulators in interest-accrual code.
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 Nubank interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →