📚

Notes on Maximum Sum Subarray and Kadane's Algorithm

Jul 28, 2024

DSA 1 Course - Lecture Notes

Introduction

  • Lecturer: Anuj
  • Topic: Arrays, focusing on Maximum Sum Subarray problem.
  • Important algorithm: Kadane's Algorithm
  • Companies that have asked this question: Paypal, Amazon, Microsoft.

Problem Definition

  • Question: Find a subarray in a given array that has the maximum sum.
  • Example Array: [-5, 4, 6, -3, 4, -1]
    • Example Subarray for maximum sum: [4, 6, -3, 4] which sums to 11.

Approach to Solve the Problem

1. Brute Force Solution

  • The brute force method involves:
    • Finding all subarrays and calculating their sums.
    • Using two nested loops to explore all possible subarrays:
      • Outer Loop: Iterate through each element
      • Inner Loop: From the current element to the end of the array
  • Time Complexity: O(n²) which is not efficient.

2. Optimizing from Brute Force

  • Considerations: You can't use sorting, as it will change the order of elements.
  • Using space doesn’t help either since it still results in O(n²) complexity.

3. Kadane's Algorithm - Efficient Approach

  • Core Idea: Start from the beginning and iteratively track the maximum sum:
    • If current sum becomes negative, reset it to 0.
    • Keep updating the maximum sum found so far.
  • Handle positive and negative elements intelligently:
    • If the total of a subarray is negative, discard it to maximize the overall sum.
    • Begin fresh from the next element if the current subarray sum goes below zero.

Example Walkthrough of Kadane's Algorithm:

  1. Start at the first element (initially 0): cursum = 0
  2. Add current element and check:
    • If cursum > maxsum, update maxsum.
    • If cursum < 0, reset cursum to 0.
  3. Continue for the entire array.
  4. Final output: maximum subarray sum.

Complexity of Kadane's Algorithm

  • Time Complexity: O(n) since it traverses the array only once.
  • Space Complexity: O(1) as it does not utilize any extra space.

Additional Tasks

  • If all elements are negative, adjustments need to be made to find the correct maximum.
    • Suggestion: Analyze and modify the existing solution accordingly.

Conclusion

  • Kadane's Algorithm is an effective method for solving the Maximum Sum Subarray problem, requiring only O(n) time complexity.
  • Homework: Consider how to modify Kadane’s Algorithm to handle arrays where all elements are negative.

Closing

  • Reminder to like, share, and subscribe to the channel for more content.
  • Thank you for attending!