Taro Logo

Maximum Subarray

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+47
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
2.2K views
Topics:
ArraysDynamic Programming

Given an integer array nums, find the subarray with the largest sum, and return its sum.

Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The subarray [4,-1,2,1] has the largest sum 6.

Example 2:

Input: nums = [1]
Output: 1
Explanation: The subarray [1] has the largest sum 1.

Example 3:

Input: nums = [5,4,-1,7,8]
Output: 23
Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.

Constraints:

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104

Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the input array contain negative numbers, or are all numbers strictly positive?
  2. What should be returned if the input array is empty?
  3. Are we guaranteed that the input array contains at least one number, or could it be null/empty?
  4. If there are multiple subarrays that share the same maximum sum, does it matter which one's sum is returned?
  5. Should I return the maximum sum itself, or do you also want me to return the starting and ending indices of the subarray?

Brute Force Solution

Approach

Imagine you have a row of numbers, some positive and some negative, and you want to find a continuous group of them that adds up to the biggest total possible. The brute force approach works by stubbornly checking every single possible starting point and ending point combination.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first number.
  2. Consider that single number as your group and calculate its total.
  3. Next, expand your group to include the very next number, and calculate the new total for this two-number group.
  4. Keep expanding your group one number at a time all the way to the end of the row, calculating the total at each step.
  5. Once you have exhausted all groups starting from the first number, move your starting point to the second number.
  6. Repeat the whole process of growing the group one number at a time and calculating its total starting from this new spot.
  7. Continue this pattern by trying every possible place to start and every possible place to stop.
  8. Keep a mental note of every total you calculate, and whenever you find a total that beats your previous record, update your record.
  9. After you have checked every single possible continuous group, your final record is the answer.

Code Implementation

def max_subarray_brute_force(numbers):    max_sum_record = float('-inf')    # Try every possible starting point for our continuous group of numbers    for start_index in range(len(numbers)):        current_group_sum = 0        # Expand the group one number at a time to evaluate all possible ending points        for end_index in range(start_index, len(numbers)):            current_group_sum += numbers[end_index]            # Update our record whenever we find a group sum that beats our previous best            if current_group_sum > max_sum_record:                max_sum_record = current_group_sum    # Return the highest total found among all evaluated continuous groups    return max_sum_record

Big(O) Analysis

Time Complexity
O(n²) – The brute force approach uses nested loops where the outer loop sets every possible starting point across the n elements, and the inner loop expands the group one number at a time to every possible ending point. For the first element, we check n groups, for the second (n-1) groups, and so on down to 1 group. This sums up to approximately n * n/2 total operations, which simplifies to a quadratic time complexity of O(n²).
Space Complexity
O(1) – The brute force approach described in the plain English explanation only relies on a few primitive variables, such as a mental note for the current total and a record for the maximum total found so far. These variables are reused across the nested iterations without creating any dynamic data structures, lists, or recursion stacks. Therefore, regardless of how large the input row of numbers grows, the extra memory required remains constant. This results in an auxiliary space complexity of O(1).

Optimal Solution

Approach

Instead of checking every single possible grouping of numbers, the optimal approach scans through the sequence once and makes smart decisions on the fly. It tracks the best total score found so far while deciding at each step whether to continue building upon the previous group or start a fresh group.

Here's how the algorithm would work step-by-step:

  1. Start looking at the numbers from the very beginning of the line.
  2. Keep a running total of the numbers you are currently looking at to see how much value they add.
  3. At every new number, decide whether it is better to team up with the previous running total or to abandon the past and start a brand new group right there.
  4. Compare your running total against the highest record you have saved so far, and update your record if the current group is better.
  5. Continue this process all the way to the end of the sequence without ever looking backward.
  6. Once you reach the very end, the highest record you saved is your final answer.

Code Implementation

def max_subarray(input_sequence):
    current_running_total = input_sequence[0]
    highest_score_record = input_sequence[0]

    # Decide whether to extend the previous group or start a fresh one at this number.
    for current_number in input_sequence[1:]:
        current_running_total = max(current_number, current_running_total + current_number)

        # Update the best record if the newly formed group outperforms the previous best.
        if current_running_total > highest_score_record:
            highest_score_record = current_running_total

    # The highest record preserved throughout the single pass is the final maximum subarray sum.
    return highest_score_record

Big(O) Analysis

Time Complexity
O(n) – The time complexity is driven by a single linear scan through the input array of size n, where we visit each number exactly once. At each step, we perform a constant number of basic arithmetic and comparison operations to update our running total and maximum record. Because we never look backward or use nested loops, the total operations scale directly with n. This results in exactly n operations, which simplifies to the final Big O time complexity of O(n).
Space Complexity
O(1) – The algorithm only uses a few primitive variables to track the running total and the highest record saved so far, regardless of the input size. No auxiliary data structures, temporary lists, or recursive stack frames are created during the process. Because these constant scalar variables require a fixed amount of memory that does not scale with the input size N, the auxiliary space complexity remains constant.

Edge Cases

Array with a single element
How to Handle:
The algorithm initializes the max sum and current sum to that single element and returns it correctly.
Array containing only negative numbers
How to Handle:
Kadanes algorithm will correctly track the smallest magnitude negative number and return it as the maximum sum.
Array with all zeros
How to Handle:
The running sum stays at zero and returns zero as the maximum contiguous subarray sum.
Extremely large array with maximum possible constraints
How to Handle:
An O(n) linear scan ensures the solution executes well within standard time limits without exceeding memory limits.
Integer overflow from very large positive numbers
How to Handle:
Using standard integer data types with max-tracking prevents overflow if sums remain within 32-bit limits, or we use language-appropriate large integer types.
Alternating positive and negative numbers
How to Handle:
The current sum resets whenever it drops below zero, ensuring we drop unprofitable prefixes and capture local peaks.
Multiple identical maximum subarrays
How to Handle:
Tracking the global maximum regardless of when it occurs guarantees we return the correct maximum sum value.
0/75 completed