Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Find Maximum Subarray Sum using Kadane's Algorithm - Optimal Solution



Problem Statement

Given an array of integers (which may include negative numbers), your task is to find the maximum sum of any contiguous subarray.

This problem is also known as the Maximum Subarray Problem.

Use Kadane's Algorithm to solve it efficiently in linear time.

Examples

Input ArrayMaximum Subarray SumDescription
[1, 2, 3, 4]10Whole array has positive values, total sum is the maximum
[-2, 1, -3, 4, -1, 2, 1, -5, 4]6Maximum sum from subarray [4, -1, 2, 1]
[-1, -2, -3, -4]-1All elements are negative; single largest number is the answer
[5]5Single element array, subarray is the element itself
[0, 0, 0]0All elements are zero, so the max subarray sum is 0
[]0Empty array returns 0 by default (no elements to sum)
[-2, -1, 0, -3]0Zero is the maximum subarray sum

Solution

The goal is to find the maximum sum of a contiguous subarray within a given array of integers. This is a classic problem and Kadane's Algorithm offers an elegant and efficient solution that works in O(n) time.

Understanding Different Cases

1. All Positive Numbers: If all elements are positive, the best strategy is to take the entire array. For example, in [1, 2, 3, 4], the answer is 10. There’s no need to exclude any elements.

2. All Negative Numbers: In cases where all numbers are negative, like [-3, -2, -1], you cannot get a positive sum. So the answer is simply the largest (least negative) number, which in this case is -1.

3. Mixed Positive and Negative: This is where Kadane's Algorithm shines. It keeps track of the current subarray sum and resets it to the current element if that element is better on its own. It also keeps updating the maximum sum seen so far. For example, in [-2, 1, -3, 4, -1, 2, 1, -5, 4], the subarray [4, -1, 2, 1] gives the maximum sum of 6.

4. Zeros or Zero as Maximum: In cases like [0, 0, 0] or [-2, -1, 0, -3], zero may be the largest value, and hence the maximum subarray sum is 0.

5. Single Element: For arrays like [5] or [-4], the result is the element itself because it's the only possible subarray.

6. Empty Array: If the array is empty, there are no elements to form a subarray, so by convention, the answer is 0.

Why Kadane’s Algorithm is Efficient

Unlike brute-force methods that check every possible subarray (which takes O(n²) time), Kadane's Algorithm only makes one pass through the array. It dynamically decides whether to extend the current subarray or start a new one, making it highly efficient.

This approach works for all types of input arrays—positive, negative, mixed, or empty—and gives you the optimal solution every time.

Visualization

Algorithm Steps

  1. Given an integer array arr.
  2. Initialize two variables: max_sum and current_sum with the value of the first element.
  3. Iterate through the array starting from index 1.
  4. At each step, update current_sum as the maximum of the current element or current_sum + current_element.
  5. Update max_sum if current_sum is greater than max_sum.
  6. After the loop, return max_sum as the result.

Code

Python
JavaScript
Java
C++
C
def max_subarray_sum(arr):
    max_sum = current_sum = arr[0]
    for num in arr[1:]:
        current_sum = max(num, current_sum + num)
        max_sum = max(max_sum, current_sum)
    return max_sum

# Sample Input
arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print("Maximum Subarray Sum:", max_subarray_sum(arr))

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(n)Even in the best case, Kadane's Algorithm must iterate through all elements of the array to compute the maximum subarray sum.
Average CaseO(n)Kadane's Algorithm processes each element once, maintaining a running sum and updating the maximum found so far in linear time.
Average CaseO(n)In all cases—whether the array has all negative values, all positives, or a mix—Kadane's algorithm completes in linear time by scanning the entire array.

Space Complexity

O(1)

Explanation: Kadane's Algorithm uses only constant space with a few variables (max_sum and current_sum) to track the state—no extra arrays or recursion are used.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M