Maximum Contiguous Subarray Sum
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Given a non-empty list of integers nums, compute the largest possible total obtainable by summing one unbroken, non-empty slice nums[left..right] (0 <= left <= right < len(nums)).
Implement max_subarray_sum(nums: List[int]) -> int to return that maximum contiguous sum. Even when every integer in nums is negative, the chosen slice must still include at least one element.
Examples
Example 1
Input: nums = [3, -5, 6, -2, 4, -1, 3, -7, 2]
Output: 10
Selecting the contiguous slice [6, -2, 4, -1, 3] (indices 2 through 6) produces 6 - 2 + 4 - 1 + 3 = 10. Extending further left (3 + (-5) = -2) or further right (-7 + 2 = -5) lowers the sum.
Example 2
Input: nums = [-9, -3, -12, -4]
Output: -3
Every value is negative and empty slices are disallowed, so the single-element slice [-3] yields the highest achievable total.
Constraints
1 <= len(nums) <= 10^5-10^9 <= nums[i] <= 10^9- Every subarray sum fits within a signed 64-bit integer.
Step-by-step walkthrough
Understand the rules and input shapes
We are given a list of integers
nums(between1and10^5elements, each between-10^9and10^9) and asked for the largest possible sum of a contiguous, non-empty subarray.Two words in the prompt control every edge case:
- Contiguous means an unbroken slice
nums[start..end]with no skipped positions. - Non-empty means the slice must contain at least one number, even if every number is negative.
nums = [ 3, -2, 5] ^-------^ valid contiguous slice [3, -2, 5] -> sum = 6 ^ ^ INVALID: skipping -2 to pick [3, 5] is not contiguous nums = [-9, -3, -12, -4] ^ valid single-element slice [-3] -> sum = -3 (empty) INVALID: [] has sum 0, but at least one element is required- Contiguous means an unbroken slice
Why checking every pair is too slow
A natural first idea is to try every starting index
start, walkendto the right while maintaining a running total, and track the largest sum seen:def brute_force(nums): best_sum = nums[0] for start in range(len(nums)): running_total = 0 for end in range(start, len(nums)): running_total += nums[end] if running_total > best_sum: best_sum = running_total return best_sumFor
nelements there aren * (n + 1) / 2pairs(start, end). Atn = 10^5, that is roughly5 * 10^9additions — thousands of times too slow. Worse, almost all of that work is duplicated: movingstartforward re-adds the same tails over and over.Key idea: ask for the best subarray ending right here
Instead of grouping subarrays by where they start, group them by where they end. Every non-empty subarray ends at some index
i. Suppose we already knowcurrent_sum, the best sum of any contiguous subarray ending ati - 1. What can the best subarray ending atilook like?There are only two possibilities for a subarray ending at
i:- Start fresh at
i: take just[nums[i]], giving sumnums[i]. - Extend from
i - 1: attachnums[i]onto a subarray ending ati - 1. To make that sum as large as possible, we should attachnums[i]onto the best subarray ending ati - 1, giving sumcurrent_sum + nums[i].
Comparing
nums[i]againstcurrent_sum + nums[i]comes down to a single sign check oncurrent_sum:Case A: current_sum < 0 (for example current_sum = -3, value = 4) extend: -3 + 4 = 1 start fresh: 4 <-- winner! A negative prefix only drags the sum down. Case B: current_sum >= 0 (for example current_sum = 4, value = -1) extend: 4 + (-1) = 3 <-- winner! Even though -1 is negative, keeping +4 start fresh: -1 leaves a positive cushion (+3) for future numbers.Once we know the best subarray ending at every index
i, the answer for the whole array is simply the largest of those values. Because stepionly needscurrent_sumfrom stepi - 1, we do not even need an array — two integers are enough. This one-pass dynamic programming technique is called Kadane's algorithm.- Start fresh at
Initialize at the first element, never at zero
Setting
best_sum = 0is a classic trap: on[-9, -3, -12, -4], every subarray has a negative sum, sobest_sumwould stay0— silently returning the sum of an empty subarray.At index
0, the only non-empty subarray ending at index0is[nums[0]]itself. Since the constraints guaranteelen(nums) >= 1,nums[0]always exists, so we initialize both variables tonums[0]and start our loop at index1:def init_trackers(nums): current_sum = nums[0] # best subarray sum ending at index 0 best_sum = nums[0] # best subarray sum seen anywhere so far return current_sum, best_sumScan from left to right in one pass
For each index
ifrom1tolen(nums) - 1, we readvalue = nums[i], updatecurrent_sumfirst (start fresh ifcurrent_sum < 0, otherwise extend), and then updatebest_sumifcurrent_sumsets a new record:def scan_subarrays(nums): current_sum = nums[0] best_sum = nums[0] for i in range(1, len(nums)): value = nums[i] if current_sum < 0: current_sum = value else: current_sum = current_sum + value if current_sum > best_sum: best_sum = current_sum return best_sumNotice why
best_sumis checked after updatingcurrent_sum: on[-1, 5], index1updatescurrent_sumto5and immediately promotesbest_sumto5. Also note number sizes:10^5elements of magnitude10^9have a total magnitude of at most10^14, which never overflows Python integers (and fits comfortably inside a 64-bit integer in C++ or Java).Trace Example 1 step by step
Let's trace
nums = [3, -5, 6, -2, 4, -1, 3, -7, 2]from start to finish:i | value | prev current_sum | decision | current_sum | active slice | best_sum ---+-------+------------------+-------------+-------------+--------------------+--------- 0 | 3 | -- | seed at i=0 | 3 | [3] | 3 1 | -5 | 3 (>= 0) | extend | -2 | [3, -5] | 3 2 | 6 | -2 (< 0) | start fresh | 6 | [6] | 6 3 | -2 | 6 (>= 0) | extend | 4 | [6, -2] | 6 4 | 4 | 4 (>= 0) | extend | 8 | [6, -2, 4] | 8 5 | -1 | 8 (>= 0) | extend | 7 | [6, -2, 4, -1] | 8 6 | 3 | 7 (>= 0) | extend | 10 | [6, -2, 4, -1, 3] | 10 7 | -7 | 10 (>= 0) | extend | 3 | [6,.., 3, -7] | 10 8 | 2 | 3 (>= 0) | extend | 5 | [6,.., -7, 2] | 10Look at
i = 3andi = 5:-2and-1lowercurrent_sumtemporarily, yet we keep extending because the positive cushion carries[6, -2, 4, -1, 3]all the way up to10ati = 6. On Example 2 ([-9, -3, -12, -4]),current_sumstarts at-9, restarts at-3(best_sum = -3), restarts at-12, restarts at-4, and returns-3.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def max_subarray_sum(nums: List[int]) -> int: # Phase 1: Seed both trackers with index 0 (not 0!), because the subarray # must contain at least one element even when every number in nums is negative. # current_sum: largest sum of a contiguous subarray that ends right at index i # best_sum: largest sum of any non-empty contiguous subarray seen in nums[0..i] current_sum = nums[0] best_sum = nums[0] # Phase 2: Sweep left to right and decide at each index whether to start fresh or extend. for i in range(1, len(nums)): value = nums[i] if current_sum < 0: # A negative running sum makes (current_sum + value) strictly smaller than value, # so dropping the old prefix and starting a new subarray [value] is always better. current_sum = value else: # A non-negative running sum helps (or ties when current_sum == 0), so extend it. current_sum = current_sum + value # Phase 3: Record whether the best subarray ending at index i beats our global record. if current_sum > best_sum: best_sum = current_sum return best_sum✅ Submit now — all tests should pass.
Intuition & how it works
Imagine walking down a street of game booths where each booth either hands you cash (a positive number) or charges a toll (a negative number), and you must visit one unbroken stretch of at least one booth — called a contiguous subarray, meaning a slice of adjacent array elements with no gaps. As you walk from booth to booth, keep track of the net profit from your current stretch (current_sum). As long as your current stretch has made zero or positive money (current_sum >= 0), carrying that balance into the next booth leaves you at least as rich as starting from scratch there; the instant your current stretch drops into debt (current_sum < 0), carrying that debt forward only hurts future totals, so you abandon the old stretch and start fresh at the next booth.
The obvious brute-force approach checks every possible (start, end) pair of indices and compares their sums. Because an array of length n has n * (n + 1) / 2 slices, n = 100,000 produces roughly 5 billion slices, which takes several seconds even when you maintain a running sum per start index. Asking "should I extend the best slice ending at i - 1, or start fresh at i?" answers every slice ending at i in a single comparison — an approach known as Kadane's algorithm (a one-pass dynamic programming method, meaning we solve a problem at each position by reusing the answer from the previous position).
Here is how the scan plays out on a tiny four-element example, nums = [-2, 4, -1, 3]:
- Index 0 (
-2): Only[-2]exists so far, socurrent_sum = -2andbest_sum = -2. - Index 1 (
4):current_sumis-2(in debt), so we drop-2and start fresh at[4]->current_sum = 4,best_sum = 4. - Index 2 (
-1):current_sumis4 >= 0, so we keep it and extend to[4, -1]->current_sum = 3,best_sumstays4. - Index 3 (
3):current_sumis3 >= 0, so we extend[4, -1]to[4, -1, 3]->current_sum = 6, updatingbest_sumto6.
Complexity
- Time: O(n). We read index
0once and then visit each of the remainingn - 1elements once in a single loop, doing one sign check, at most one addition, and one comparison per element. - Space: O(1) extra space. Computing the best subarray ending at index
ionly requirescurrent_sumfrom indexi - 1, so we store just a few scalar variables (current_sum,best_sum,i,value) regardless of how largenumsgrows.
Edge cases
- Single-element array:
[5]returns5and[-7]returns-7, because the loop overrange(1, len(nums))does not run andbest_sumstarts atnums[0]. - All negative numbers:
[-9, -3, -12, -4]returns-3(the least negative single element), because empty subarrays are forbidden and every step seescurrent_sum < 0and restarts. - All positive numbers:
[1, 2, 3, 4]never seescurrent_sum < 0, so it keeps extending and returns the sum of the entire array (10). - Zeros mixed with negatives:
[-3, 0, -1]restarts at0and returns0from the valid single-element subarray[0]. - Ties between multiple subarrays:
[1, -1, 1]has three subarrays with sum1([1]at index 0,[1]at index 2, and[1, -1, 1]), and all produce the same maximum sum1. - Large magnitudes near
+-10^9: With10^5elements of magnitude10^9,|current_sum|can reach10^14. Python integers have arbitrary precision; in C++, Java, or Go,current_sumandbest_summust use a 64-bit signed integer (long long/long) rather than 32-bitint(which overflows around2.1 * 10^9).
Common mistakes
- Initializing
best_sum = 0instead ofnums[0]: On an all-negative input like[-9, -3, -12, -4],best_sumnever gets beat and wrongly returns0(an empty subarray). - Restarting whenever
nums[i] < 0instead of whencurrent_sum < 0: In[3, -2, 5],-2is negative, yet keeping[3, -2]leaves a positive balance of+1that connects3and5into sum6. Only restart when the running sum turns negative. - Summing only the positive numbers: Picking
3 + 5 = 8from[3, -2, 5]computes a maximum subsequence sum (skipping elements), violating the contiguity rule. - Updating
best_sumbefore updatingcurrent_sum: Checkingbest_sumat the top of the loop misses the final element ([-1, 5]would return-1instead of5).
Alternative approaches
- Prefix sums (O(n) time, O(1) space): A prefix sum is the running total from the start of the array up to index
i(prefix[i + 1] = nums[0] + ... + nums[i]). Every subarray sumnums[start..end]equalsprefix[end + 1] - prefix[start], so maximizing the sum ending atendmeans subtracting the smallest prefix sum seen so far (min_prefix). Trackingprefixandmin_prefixon the fly does the exact same work as Kadane's algorithm from a different viewpoint. - Divide and conquer (O(n log n) time, O(log n) recursion stack): Divide and conquer splits the array in half recursively and combines answers from the two halves. The best subarray lies wholly in the left half, wholly in the right half, or crosses the midpoint (best suffix of the left half plus best prefix of the right half, found in
O(n)). Although slower for a static array, storing four numbers per block (total_sum,best_prefix,best_suffix,best_subarray) powers a segment tree — a binary tree over array ranges that supports point updates and range maximum-subarray queries inO(log n)time each.
Follow-up questions
- What extra state do you need if the caller also wants the
[left, right]boundaries of the winning subarray? Maintaincurrent_start = 0alongsidecurrent_sum, resettingcurrent_start = iwhenevercurrent_sum < 0forces a fresh subarray start. Each timecurrent_sum > best_sum, copybest_start = current_startandbest_end = iso the recorded endpoints stay synchronized withbest_sum(strict>preserves the earliest tie-winner; clarify with the interviewer whether earliest, shortest, or latest is desired).
python
def max_subarray_with_indices(nums):
current_sum = nums[0]
best_sum = nums[0]
current_start = 0
best_start = 0
best_end = 0
for i in range(1, len(nums)):
if current_sum < 0:
current_sum = nums[i]
current_start = i
else:
current_sum += nums[i]
if current_sum > best_sum:
best_sum = current_sum
best_start = current_start
best_end = i
return best_sum, best_start, best_end
- How does the algorithm change when the array wraps around into a ring so a subarray may span across the last element back into the first? Any valid ring slice either stays within
0..n - 1without wrapping (best sumbest_maxfrom standard Kadane) or wraps across the seam (taking a suffix plus a prefix, which omits one contiguous interior block). Maximizing a wrapping slice equalssum(nums) - best_min, wherebest_minis the minimum contiguous subarray sum, givingmax(best_max, sum(nums) - best_min)inO(n)time andO(1)space—with one essential guard: whenbest_max < 0(all elements are negative),best_min == sum(nums)sosum(nums) - best_min == 0would represent an empty slice, meaning we must returnbest_maxdirectly.
python
def max_circular_subarray_sum(nums):
cur_max = best_max = nums[0]
cur_min = best_min = nums[0]
total = nums[0]
for i in range(1, len(nums)):
val = nums[i]
total += val
cur_max = val if cur_max < 0 else cur_max + val
best_max = max(best_max, cur_max)
cur_min = val if cur_min > 0 else cur_min + val
best_min = min(best_min, cur_min)
if best_max < 0:
return best_max
return max(best_max, total - best_min)
- Why can no deterministic or randomized algorithm beat
O(n)time andO(1)auxiliary space in the worst case? Consider an input filled withncopies of-10(true answer-10). If any algorithm finishes without reading at least one indexk, an adversary can replacenums[k]with+100(raising the true answer to+100) without altering a single value the algorithm observed, forcing an error on one of the two inputs—proving anOmega(n)time lower bound. Meanwhile,O(1)extra working memory is already the smallest space class possible.
Follow-up questions
- What extra state do you need if the caller also wants the `[left, right]` boundaries of the winning subarray?
- How does the algorithm change when the array wraps around into a ring so a subarray may span across the last element back into the first?
- Why can no deterministic or randomized algorithm beat `O(n)` time and `O(1)` auxiliary space in the worst case?
Similar questions
- Two-Thread Odd-Even Sequence Coordinator
- Palindrome Check on a Singly Linked List
- Locate a Celebrity Using an Acquaintance Matrix
- Collapse Adjacent Duplicate Letters
- System Architecture Walkthrough and Your Toughest Design Trade-Off
- Navigating Two High-Stakes Commitments on Colliding Timelines
More Omnissa interview questions
- Palindrome Check on a Singly Linked List Medium
- Locate a Celebrity Using an Acquaintance Matrix Medium
- System Architecture Walkthrough and Your Toughest Design Trade-Off Medium Pro
- Navigating Two High-Stakes Commitments on Colliding Timelines Medium Pro
- Two-Thread Odd-Even Sequence Coordinator Medium Pro
- Collapse Adjacent Duplicate Letters Medium Pro