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] <= 104Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
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:
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:
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_recordInstead 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:
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| Case | How to Handle |
|---|---|
| Array with a single element | The algorithm initializes the max sum and current sum to that single element and returns it correctly. |
| Array containing only negative numbers | Kadanes algorithm will correctly track the smallest magnitude negative number and return it as the maximum sum. |
| Array with all zeros | The running sum stays at zero and returns zero as the maximum contiguous subarray sum. |
| Extremely large array with maximum possible constraints | 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 | 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 | The current sum resets whenever it drops below zero, ensuring we drop unprofitable prefixes and capture local peaks. |
| Multiple identical maximum subarrays | Tracking the global maximum regardless of when it occurs guarantees we return the correct maximum sum value. |