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

  1. Understand the rules and input shapes

    We are given a list of integers nums (between 1 and 10^5 elements, each between -10^9 and 10^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
    
  2. Why checking every pair is too slow

    A natural first idea is to try every starting index start, walk end to 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_sum
    

    For n elements there are n * (n + 1) / 2 pairs (start, end). At n = 10^5, that is roughly 5 * 10^9 additions — thousands of times too slow. Worse, almost all of that work is duplicated: moving start forward re-adds the same tails over and over.

  3. 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 know current_sum, the best sum of any contiguous subarray ending at i - 1. What can the best subarray ending at i look like?

    There are only two possibilities for a subarray ending at i:

    1. Start fresh at i: take just [nums[i]], giving sum nums[i].
    2. Extend from i - 1: attach nums[i] onto a subarray ending at i - 1. To make that sum as large as possible, we should attach nums[i] onto the best subarray ending at i - 1, giving sum current_sum + nums[i].

    Comparing nums[i] against current_sum + nums[i] comes down to a single sign check on current_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 step i only needs current_sum from step i - 1, we do not even need an array — two integers are enough. This one-pass dynamic programming technique is called Kadane's algorithm.

  4. Initialize at the first element, never at zero

    Setting best_sum = 0 is a classic trap: on [-9, -3, -12, -4], every subarray has a negative sum, so best_sum would stay 0 — silently returning the sum of an empty subarray.

    At index 0, the only non-empty subarray ending at index 0 is [nums[0]] itself. Since the constraints guarantee len(nums) >= 1, nums[0] always exists, so we initialize both variables to nums[0] and start our loop at index 1:

    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_sum
    
  5. Scan from left to right in one pass

    For each index i from 1 to len(nums) - 1, we read value = nums[i], update current_sum first (start fresh if current_sum < 0, otherwise extend), and then update best_sum if current_sum sets 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_sum
    

    Notice why best_sum is checked after updating current_sum: on [-1, 5], index 1 updates current_sum to 5 and immediately promotes best_sum to 5. Also note number sizes: 10^5 elements of magnitude 10^9 have a total magnitude of at most 10^14, which never overflows Python integers (and fits comfortably inside a 64-bit integer in C++ or Java).

  6. 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]      |    10
    

    Look at i = 3 and i = 5: -2 and -1 lower current_sum temporarily, yet we keep extending because the positive cushion carries [6, -2, 4, -1, 3] all the way up to 10 at i = 6. On Example 2 ([-9, -3, -12, -4]), current_sum starts at -9, restarts at -3 (best_sum = -3), restarts at -12, restarts at -4, and returns -3.

  7. 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, so current_sum = -2 and best_sum = -2.
  • Index 1 (4): current_sum is -2 (in debt), so we drop -2 and start fresh at [4] -> current_sum = 4, best_sum = 4.
  • Index 2 (-1): current_sum is 4 >= 0, so we keep it and extend to [4, -1] -> current_sum = 3, best_sum stays 4.
  • Index 3 (3): current_sum is 3 >= 0, so we extend [4, -1] to [4, -1, 3] -> current_sum = 6, updating best_sum to 6.

Complexity

  • Time: O(n). We read index 0 once and then visit each of the remaining n - 1 elements 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 i only requires current_sum from index i - 1, so we store just a few scalar variables (current_sum, best_sum, i, value) regardless of how large nums grows.

Edge cases

  • Single-element array: [5] returns 5 and [-7] returns -7, because the loop over range(1, len(nums)) does not run and best_sum starts at nums[0].
  • All negative numbers: [-9, -3, -12, -4] returns -3 (the least negative single element), because empty subarrays are forbidden and every step sees current_sum < 0 and restarts.
  • All positive numbers: [1, 2, 3, 4] never sees current_sum < 0, so it keeps extending and returns the sum of the entire array (10).
  • Zeros mixed with negatives: [-3, 0, -1] restarts at 0 and returns 0 from the valid single-element subarray [0].
  • Ties between multiple subarrays: [1, -1, 1] has three subarrays with sum 1 ([1] at index 0, [1] at index 2, and [1, -1, 1]), and all produce the same maximum sum 1.
  • Large magnitudes near +-10^9: With 10^5 elements of magnitude 10^9, |current_sum| can reach 10^14. Python integers have arbitrary precision; in C++, Java, or Go, current_sum and best_sum must use a 64-bit signed integer (long long / long) rather than 32-bit int (which overflows around 2.1 * 10^9).

Common mistakes

  • Initializing best_sum = 0 instead of nums[0]: On an all-negative input like [-9, -3, -12, -4], best_sum never gets beat and wrongly returns 0 (an empty subarray).
  • Restarting whenever nums[i] < 0 instead of when current_sum < 0: In [3, -2, 5], -2 is negative, yet keeping [3, -2] leaves a positive balance of +1 that connects 3 and 5 into sum 6. Only restart when the running sum turns negative.
  • Summing only the positive numbers: Picking 3 + 5 = 8 from [3, -2, 5] computes a maximum subsequence sum (skipping elements), violating the contiguity rule.
  • Updating best_sum before updating current_sum: Checking best_sum at the top of the loop misses the final element ([-1, 5] would return -1 instead of 5).

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 sum nums[start..end] equals prefix[end + 1] - prefix[start], so maximizing the sum ending at end means subtracting the smallest prefix sum seen so far (min_prefix). Tracking prefix and min_prefix on 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 in O(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? Maintain current_start = 0 alongside current_sum, resetting current_start = i whenever current_sum < 0 forces a fresh subarray start. Each time current_sum > best_sum, copy best_start = current_start and best_end = i so the recorded endpoints stay synchronized with best_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 - 1 without wrapping (best sum best_max from standard Kadane) or wraps across the seam (taking a suffix plus a prefix, which omits one contiguous interior block). Maximizing a wrapping slice equals sum(nums) - best_min, where best_min is the minimum contiguous subarray sum, giving max(best_max, sum(nums) - best_min) in O(n) time and O(1) space—with one essential guard: when best_max < 0 (all elements are negative), best_min == sum(nums) so sum(nums) - best_min == 0 would represent an empty slice, meaning we must return best_max directly.

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 and O(1) auxiliary space in the worst case? Consider an input filled with n copies of -10 (true answer -10). If any algorithm finishes without reading at least one index k, an adversary can replace nums[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 an Omega(n) time lower bound. Meanwhile, O(1) extra working memory is already the smallest space class possible.

Follow-up questions

Similar questions

More Omnissa interview questions

All 7 Omnissa questions →