Maximum Subarray Sum with Kadane's Algorithm



In this problem, we are given an array of integers that may contain both positive and negative integers. We have to calculate the maximum sum of any contiguous subarray of the given array. In this article, we are going to learn how we can find the maximum subarray sum using the Kadane Algorithm using C#. Here is an example to find maximum sum in subarray:

Example

Input:
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 

Output:
Maximum Subarray Sum: 9

Here are the two approaches to find the maximum subarray sum:

Using the Brute Force Approach

This is the simple and direct approach to check all possible sub-arrays and calculate the sum of the maximum subarray sum. In this approach, we traverse through all possible

  • Define a function to take an input array as a parameter.
  • Now, use nested loops to generate all possible sub-arrays.
  • Calculate the sum of each subarray and keep track of the maximum sum.
  • Return the maximum subarray sum.

Example

The following example implements above code to find the maximum subarray sum using brute force approach:

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 };

        // Print the array
        Console.WriteLine("Array: " + string.Join(", ", arr));

        // Print the maximum subarray sum
        Console.WriteLine("Maximum Subarray Sum is: " + MaxSubarraySum(arr));
    }
}

The output of the above code:

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

Time Complexity:O(n2) Space Complexity:O(1)

Using Kadane's Algorithm

This is a more efficient approach, which reduces the time complexity to linear time, i.e., O(n). This approach provides an efficient way to find the maximum subarray sum in a single loop.

  • Define a function and take the array as an input parameter.
  • Initialize maxSum and currentSum variables to the smallest possible integer value and 0, respectively.
  • Iterate through the array and update currentSum.
  • If currentSum is greater than maxSum, update maxSum.
  • If currentSum becomes negative, reset it to zero.
  • Return maxSum.

Example

The following example implements above code to find the maximum subarray sum using brute Kadane algorithm:

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 };
        
        // Print the array
        Console.WriteLine("Array: " + string.Join(", ", arr));

        // Print the maximum subarray sum
        Console.WriteLine("Maximum Subarray Sum is: " + KadaneAlgorithm(arr));
    }
}

The output of the above code:

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

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

Updated on: 2025-04-21T14:40:12+05:30

154 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements