How to find the maximum subarray sum using the greedy approach

Key takeaways:

  • Kadane’s algorithm for maximum subarray sum: This problem is efficiently solved using Kadaness Algorithm with time complexity of O(n)O(n), making it suitable for large input arrays.

  • Dynamic subarray management: The algorithm dynamically keeps track of the maximum subarray sum as it iterates through the array, updating the result when a higher sum is found.

  • Optimal for handling mixed positive and negative numbers: Kadane’s Algorithm is designed to handle arrays with both positive and negative numbers, ensuring the maximum sum subarray is identified even when negative values are present.

  • Frequently asked in coding interviews: Problems involving finding the maximum subarray sum are common in technical interviews at top tech companies like Google, Microsoft, and Facebook.

  • Real-world applications: This algorithm has applications in areas like stock market analysis, weather prediction, and any scenario where finding the maximum sum of consecutive elements is important.

  • Algorithmic efficiency: Kadane’s Algorithm is an optimal, linear-time solution, demonstrating the importance of efficiency in solving real-world problems.

What is a maximum subarray sum?

The maximum subarray sum is the largest possible sum of a contiguous subarray within a given array. The subarray can consist of any number of consecutive elements, and the goal is to find the subarray that yields the highest sum.

Problem statement

Given an array of integers, nums, find the sum of a subarraya contiguous subset of an array that contains at least one element and has the greatest sum of all the subarrays.

Let’s understand this with the help of an example array [-3, 1, -2, 5, 0, 3, 2, -4, 6]. Out of all the possible subarrays, the subarray, [5, 0, 3, 2, -4, 6], produces a maximum sum of 12, so the output of this input will be 12.

Constraints:

  • 11 \leq nums.length 103\leq 10^3

  • 104-10^4 \leq nums[i] 104\leq 10^4

Example

canvasAnimation-image
1 of 3

Knowledge test

Let’s take a moment to ensure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem.

Maximum subarray sum

1

What is the output if the following array is given as input to the greedy approach for finding the maximum subarray sum?

nums = [1, 2, 2, 3, 3, 1, 4]

A)

12

B)

8

C)

7

D)

9

Question 1 of 30 attempted

The solution to the maximum subarray sum problem

The maximum subarray sum problem can be efficiently solved using Kadane’s algorithm, a greedy approach that simplifies the decision-making process for finding the maximum sum of a contiguous subarray. The idea behind this approach is to iteratively decide whether to continue adding the current element to the existing subarray or start a new subarray. This decision is based on whether the current sum would be better by adding the current element or resetting the sum to just the current element itself.

In Kadane’s algorithm, we maintain two variables: the current subarray sum and the global maximum sum encountered so far. Starting from the first element, we check if adding the current element to the existing sum will increase it. If adding it makes the sum smaller, we reset the current sum to just the current element, effectively starting a new subarray. We continuously update the global maximum sum if the current sum exceeds it.

Here’s the detailed algorithm for the approach we just discussed:

  1. Initialization:

    1. We initialize a varaible curr_max to the first element of the array, representing the current subarray sum.

    2. We’ll also initalize global_max to point the first element, representing the highest subarray sum encountered so far.

  2. Iterating through the array:

    1. We’ll traverse from the second element (index 1) and process each element:

      1. If curr_max becomes negative, we reset it to the current element, starting a new subarray.

      2. Otherwise, we add the current element to curr_max, extending the current subarray.

      3. After updating curr_max, we’ll compare it with global_max. If curr_max exceeds global_max, the global maximum is updated.

  3. Return the result:

    1. Once the loop finishes, we return global_max, which holds the maximum sum of any contiguous subarray.

Let’s look at the illustration below to better understand the solution:

canvasAnimation-image
1 of 10

Let’s look at the Python code for this solution below:

def find_max_sum_sublist(nums):
if len(nums) < 1:
return 0
# Initialize the current subarray sum and the global maximum sum
curr_max = nums[0]
global_max = nums[0]
# Iterate through the array starting from the second element
for i in range(1, len(nums)):
# If the current subarray sum becomes negative, start a new subarray
if curr_max < 0:
curr_max = nums[i] # Reset the current subarray sum to the current element
else:
curr_max += nums[i] # Otherwise, extend the current subarray sum
# Update the global maximum sum if the current subarray sum is larger
if global_max < curr_max:
global_max = curr_max # Update global max with the larger sum
return global_max # Return the maximum subarray sum found
def main():
inputs = [
[1, -2, 3, 4, -1, 2, 1, -5, 4],
[-2, -3, -4, -1, -2],
[5, 4, 3, 2, 1],
[-3, -1, -1, -2, -2, 1, 3],
[10, -5, 2, 3, -1, -2, 6],
[1]
]
for i in range(len(inputs)):
print(i + 1, ".\tInput array: ", inputs[i], sep="")
print("\tMaximum subbary sum: ", find_max_sum_sublist(inputs[i]), sep="")
print("-" * 100)
if __name__ == "__main__":
main()
Maximum subarray sum

Complexity analysis

Time complexity: Since we are only looping through the array once, the algorithm’s time complexity is O(n)O(n), where n is the length of the array.

Space complexity: The space complexity of this algorithm is O(1)O(1), as we don’t need any additional memory (other than variables to store currentSum and maximumSum).

Why does the greedy approach work?

  1. The greedy strategy ensures that negative subarrays are ignored early, allowing the algorithm to focus on positive-sum subarrays.

  2. The running total (currentSum) and a comparison with the global maximum (maximumSum) guarantee the largest sum is found.

Additional resources

To learn more about data structures and algorithms and practice more LeetCode-based problems. Look at the following list of curated courses at Educative:

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is Kadane’s Algorithm?

Kadane’s Algorithm is an efficient algorithm for finding the maximum sum of a contiguous subarray within a one-dimensional numerical array. It operates in O(n)O(n) time, making it one of the most optimal solutions for this problem.


Can the algorithm handle negative numbers?

Yes, the algorithm works with negative numbers. If all numbers in the array are negative, it will return the largest (least negative) number as the maximum sum, which is the correct answer for such cases.


Can this algorithm be used for a problem with circular subarrays?

No, this algorithm is for linear subarrays. For circular subarrays (where the subarray can wrap around), a modified version of Kadane’s Algorithm, along with a calculation for the total sum and the minimum subarray sum, is needed.


What is the maximum sum subarray problem commonly used for?

The maximum subarray problem is commonly used in dynamic programming and optimization tasks, such as solving problems in financial markets (finding the best time to buy/sell stocks), image processing (finding the most significant segment of an image), and more.


Free Resources