KADANE'S ALGORITHM

 

Maximum Subarray Sum – Kadane’s Algorithm 

Introduction

The maximum subarray sum problem is a classic problem in programming. The goal is to find the maximum possible sum of a contiguous subarray within a given array.

A subarray must contain at least one element and must be continuous.

Problem Statement

Given an array arr[], find the maximum sum of any subarray.

Example

Input:

arr = [2, 3, -8, 7, -1, 2, 3]

Output:

11

Explanation:
Subarray [7, -1, 2, 3] gives the maximum sum = 11

Solution Code

class Solution:
    def maxSubarraySum(self, arr):
        max_sum = arr[0]
        current_sum = arr[0]

        for i in range(1, len(arr)):
            current_sum = max(arr[i], current_sum + arr[i])
            max_sum = max(max_sum, current_sum)

        return max_sum

Approach Used: Kadane’s Algorithm

Idea

At each step, we decide:

  • Either continue the current subarray

  • Or start a new subarray from the current element

How It Works

  1. Initialize:

    • current_sum = arr[0]

    • max_sum = arr[0]

  2. Traverse the array:

    • For each element:

      • Update current_sum:

        • Either take current element alone

        • Or add it to previous sum

      • Update max_sum if needed

  3. Return max_sum

Why This Approach Was Chosen

  • Efficient: Only one pass through the array

  • Handles both positive and negative numbers

  • Avoids checking all subarrays (which is costly)

Alternative Approaches

  • Brute Force (Check all subarrays)
    Time Complexity: O(n²)
     Very slow for large inputs

  • Divide and Conquer
    More complex and less intuitive

Why Kadane’s Algorithm?
Because it provides the best time complexity (O(n)) with simple logic.

Time and Space Complexity

  • Time Complexity: O(n)

  • Space Complexity: O(1)

Important Observation

  • Even if all elements are negative, the algorithm still works

  • It returns the maximum single element in such cases

Conclusion

Kadane’s Algorithm is the most efficient way to solve the maximum subarray sum problem. It simplifies the problem by making local decisions at each step, resulting in a global maximum. This makes it a widely used and important algorithm in problem-solving.

Comments

Popular posts from this blog

THE DELIVERY MAN

EC2 LAUNCHING

SORT A LINKED LIST USING MERGE SORT