C/C++ Program for Largest Sum Contiguous Subarray?

An array of integers is given. We have to find the sum of all contiguous elements whose sum is largest. This problem is known as the Maximum Subarray Problem and is efficiently solved using Kadane's Algorithm.

Using dynamic programming, we store the maximum sum up to the current element. This helps find the optimal contiguous subarray with maximum sum.

Syntax

int maxSubarraySum(int arr[], int n);

Algorithm: Kadane's Algorithm

The algorithm maintains two variables −

Input: An array of integers. {-2, -3, 4, -1, -2, 1, 5, -3}
Output: Maximum Sum of the Subarray is: 7

Steps

Begin
   maxSoFar := array[0]
   maxEndingHere := array[0]
   for i := 1 to n-1, do
      maxEndingHere = maximum of (array[i], maxEndingHere + array[i])
      maxSoFar = maximum of (maxSoFar, maxEndingHere)
   done
   return maxSoFar
End

Example

Here's the implementation of Kadane's algorithm in C −

#include <stdio.h>

int maxSubarraySum(int arr[], int n) {
    int maxSoFar = arr[0];
    int maxEndingHere = arr[0];
    
    for (int i = 1; i < n; i++) {
        /* Either extend the existing subarray or start new subarray */
        if (maxEndingHere + arr[i] > arr[i]) {
            maxEndingHere = maxEndingHere + arr[i];
        } else {
            maxEndingHere = arr[i];
        }
        
        /* Update maximum sum found so far */
        if (maxEndingHere > maxSoFar) {
            maxSoFar = maxEndingHere;
        }
    }
    
    return maxSoFar;
}

int main() {
    int arr[] = {-2, -3, 4, -1, -2, 1, 5, -3};
    int n = 8;
    
    printf("Array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    printf("Maximum Sum of the Subarray is: %d\n", maxSubarraySum(arr, n));
    
    return 0;
}
Array: -2 -3 4 -1 -2 1 5 -3 
Maximum Sum of the Subarray is: 7

How It Works

The algorithm works by deciding at each position whether to −

  • Extend the current subarray by including the current element
  • Start a new subarray from the current element

For the given example {-2, -3, 4, -1, -2, 1, 5, -3}, the optimal subarray is {4, -1, -2, 1, 5} with sum = 7.

Key Points

  • Time Complexity: O(n) − single pass through the array
  • Space Complexity: O(1) − only two variables used
  • Works for arrays with all negative numbers
  • This is an optimal solution known as Kadane's Algorithm

Conclusion

Kadane's algorithm efficiently solves the maximum subarray problem in linear time using dynamic programming. It's optimal for finding the largest sum of any contiguous subarray within a given array.

Updated on: 2026-03-15T10:55:21+05:30

527 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements