Maximum Subarray Sum - Kadane Algorithm using C#

The Maximum Subarray Sum problem involves finding the contiguous subarray within a given array of integers that has the largest sum. Kadane's Algorithm is the most efficient approach to solve this problem in linear time.

Given an array that may contain both positive and negative integers, we need to find the maximum sum of any contiguous subarray. Here is an example

<strong>Input:</strong>
arr = [1, -2, 3, 4, -1, 2, 1, -5, 4]

Maximum Sum Subarray: [3, 4, -1, 2, 1]
Sum = 3 + 4 + (-1) + 2 + 1 = 9

<strong>Output:</strong>
Maximum Subarray Sum: 9

There are two main approaches to solve this problem

  • Brute Force Approach Check all possible subarrays
  • Kadane's Algorithm Efficient linear time solution

Maximum Subarray Sum Visualization 1 -2 3 4 -1 2 1 -5 4 Maximum Subarray Array: [1, -2, 3, 4, -1, 2, 1, -5, 4] Maximum Subarray: [3, 4, -1, 2, 1] = 9 Kadane's Algorithm finds this in O(n) time by tracking current sum and maximum sum

Using Brute Force Approach

The brute force approach examines all possible subarrays and calculates their sums to find the maximum. This method uses three nested loops to generate and evaluate every contiguous subarray.

Algorithm Steps

  • Use nested loops to generate all possible subarrays
  • Calculate the sum of each subarray
  • Keep track of the maximum sum encountered
  • Return the maximum subarray sum

Example

using System;

class Program {
    static int MaxSubarraySum(int[] arr) {
        int maxSum = int.MinValue;
        int n = arr.Length;

        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
                int sum = 0;
                for (int k = i; k <= j; k++) {
                    sum += arr[k];
                }
                maxSum = Math.Max(maxSum, sum);
            }
        }
        return maxSum;
    }

    static void Main() {
        int[] arr = { 1, -2, 3, 4, -1, 2, 1, -5, 4 };
        
        Console.WriteLine("Array: " + string.Join(", ", arr));
        Console.WriteLine("Maximum Subarray Sum: " + MaxSubarraySum(arr));
    }
}

The output of the above code is

Array: 1, -2, 3, 4, -1, 2, 1, -5, 4
Maximum Subarray Sum: 9

Time Complexity: O(n³) | Space Complexity: O(1)

Using Kadane's Algorithm

Kadane's Algorithm is an efficient dynamic programming approach that solves the maximum subarray problem in linear time. It maintains a running sum of the current subarray and updates the maximum sum whenever a larger sum is found.

Algorithm Steps

  • Initialize maxSum to the smallest integer and currentSum to 0
  • Iterate through the array, adding each element to currentSum
  • Update maxSum if currentSum is greater
  • Reset currentSum to 0 if it becomes negative
  • Return the maxSum

Example with Mixed Numbers

using System;

class Program {
    static int KadaneAlgorithm(int[] arr) {
        int maxSum = int.MinValue;
        int currentSum = 0;

        foreach (int num in arr) {
            currentSum += num;
            maxSum = Math.Max(maxSum, currentSum);
            
            if (currentSum < 0) {
                currentSum = 0;
            }
        }
        return maxSum;
    }

    static void Main() {
        int[] arr = { 1, -2, 3, 4, -1, 2, 1, -5, 4 };
        
        Console.WriteLine("Array: " + string.Join(", ", arr));
        Console.WriteLine("Maximum Subarray Sum: " + KadaneAlgorithm(arr));
    }
}

The output of the above code is

Array: 1, -2, 3, 4, -1, 2, 1, -5, 4
Maximum Subarray Sum: 9

Example with All Negative Numbers

using System;

class Program {
    static int KadaneAlgorithm(int[] arr) {
        int maxSum = int.MinValue;
        int currentSum = 0;

        foreach (int num in arr) {
            currentSum += num;
            maxSum = Math.Max(maxSum, currentSum);
            
            if (currentSum < 0) {
                currentSum = 0;
            }
        }
        return maxSum;
    }

    static void Main() {
        int[] arr = { -1, -2, -3, -4 };
        
        Console.WriteLine("Array: " + string.Join(", ", arr));
        Console.WriteLine("Maximum Subarray Sum: " + KadaneAlgorithm(arr));
    }
}

The output of the above code is

Array: -1, -2, -3, -4
Maximum Subarray Sum: -1

Time Complexity: O(n) | Space Complexity: O(1)

Comparison

Approach Time Complexity Space Complexity Best For
Brute Force O(n³) O(1) Small arrays, learning purposes
Kadane's Algorithm O(n) O(1) Large arrays, production code

Conclusion

Kadane's Algorithm provides an optimal O(n) solution for the maximum subarray sum problem, making it significantly more efficient than the brute force approach. The algorithm elegantly handles both positive and negative numbers by maintaining a running sum and resetting when the sum becomes negative.

Updated on: 2026-03-17T07:04:36+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements