Open In App

Maximum Subarray Sum in C++

Last Updated : 26 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn how to find the maximum sum of a contiguous subarray within a given array of integers in C++ language. Finding the maximum subarray sum involves determining the contiguous subarray that has the largest sum.

Example:

Input:
arr[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4}

Output:
6

Explanation: The subarray [4, -1, 2, 1] has the largest sum of 6.
kadane-Algorithm_img
Largest Sum Contiguous subarray 

Method 1: Brute Force Approach

In this method, we consider every possible subarray and calculate the sum of elements in each subarray. We then return the maximum sum among all subarrays.

Approach:

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

Below is the implementation of the above approach:

C++
// C++ program to find the maximum subarray sum using a
// brute-force approach

#include <climits>
#include <iostream>

using namespace std;

// Function to find the maximum subarray sum
int maxSubArraySum(int arr[], int n)
{
    int maxSum = INT_MIN;

    // Iterate through each element as the starting point
    for (int i = 0; i < n; i++) {
        int currentSum = 0;

        // Iterate through the rest of the elements
        for (int j = i; j < n; j++) {
            currentSum += arr[j];

            // Update maxSum if the current sum is greater
            if (currentSum > maxSum) {
                maxSum = currentSum;
            }
        }
    }

    return maxSum;
}

int main()
{
    // Array of integers
    int arr[] = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);

    // Find and print the maximum subarray sum
    cout << "Maximum Subarray Sum is "
         << maxSubArraySum(arr, n) << endl;

    return 0;
}

Output
Maximum Subarray Sum is 6

Time Complexity: O(N^2)
Auxiliary Space: O(1)

Method 2: Using Kadane’s Algorithm

Kadane’s Algorithm provides an efficient way to find the maximum subarray sum in linear time by maintaining a running sum of the subarray and updating the maximum sum encountered so far.

Approach:

  • Initialize max_so_far and max_ending_here to the first element of the array.
  • Iterate through the array, updating max_ending_here to be the maximum of the current element and the sum of max_ending_here and the current element.
  • Update max_so_far to be the maximum of max_so_far and max_ending_here.
  • Return max_so_far.
Maximum-Sum-Subarray-(-Kadane's-Algorithm)-(2)

Below is the implementation of the above approach:

C++
// C++ program to find the maximum subarray sum using
// Kadane's Algorithm

#include <climits>
#include <iostream>

using namespace std;

// Function to find the maximum subarray sum using Kadane's
// Algorithm
int maxSubArraySum(int arr[], int n)
{
    int max_so_far = arr[0];
    int max_ending_here = arr[0];

    // Iterate through the array starting from the second
    // element
    for (int i = 1; i < n; i++) {
        // Update max_ending_here by including the current
        // element
        max_ending_here
            = max(arr[i], max_ending_here + arr[i]);

        // Update max_so_far to be the maximum of itself and
        // max_ending_here
        max_so_far = max(max_so_far, max_ending_here);
    }

    return max_so_far;
}

int main()
{
    // Array of integers
    int arr[] = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);

    // Find and print the maximum subarray sum
    cout << "Maximum Subarray Sum is "
         << maxSubArraySum(arr, n) << endl;

    return 0;
}

Output
Maximum Subarray Sum is 6

Time Complexity: O(N)
Auxiliary Space: O(1)

Method 3: Printing the Largest Sum Contiguous Subarray

To print the subarray with the maximum sum, we maintain the start index of the maximum sum subarray. When the maximum sum is updated, we also update the start and end indices of the subarray.

Approach:

  • Initialize variables s, start, and end with 0, and max_so_far with INT_MIN and max_ending_here with 0.
  • Traverse the array:
    • Add the current element to max_ending_here.
    • If max_so_far is less than max_ending_here, update max_so_far, start, and end.
    • If max_ending_here is less than 0, reset max_ending_here to 0 and update s.
  • Print the values from index start to end.

Below is the implementation of the above approach:

C++
// C++ program to find the maximum subarray sum along with
// its starting and ending indices

#include <climits>
#include <iostream>

using namespace std;

// Function to find the maximum subarray sum with its
// starting and ending indices
void maxSubArraySum(int a[], int size)
{
    int max_so_far = INT_MIN, max_ending_here = 0;
    int start = 0, end = 0, s = 0;

    // Iterate through the array
    for (int i = 0; i < size; i++) {
        // Update max_ending_here by including the current
        // element
        max_ending_here += a[i];

        // Update max_so_far and the indices if a new
        // maximum is found
        if (max_so_far < max_ending_here) {
            max_so_far = max_ending_here;
            start = s;
            end = i;
        }

        // Reset max_ending_here and update the potential
        // starting index if max_ending_here becomes
        // negative
        if (max_ending_here < 0) {
            max_ending_here = 0;
            s = i + 1;
        }
    }

    // Print the results
    cout << "Maximum contiguous sum is " << max_so_far
         << endl;
    cout << "Starting index " << start << endl;
    cout << "Ending index " << end << endl;
}

int main()
{
    // Array of integers
    int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 };
    int n = sizeof(a) / sizeof(a[0]);

    // Find and print the maximum subarray sum along with
    // its starting and ending indices
    maxSubArraySum(a, n);

    return 0;
}

Output
Maximum contiguous sum is 7
Starting index 2
Ending index 6

Time Complexity: O(N)
Auxiliary Space: O(1)

Method 4: Dynamic Programming Approach

For each index i, DP[i] stores the maximum possible sum of a contiguous subarray ending at index i. We use the state transition DP[i] = max(DP[i-1] + arr[i], arr[i]).

Approach:

  • Initialize a DP array where DP[i] is the maximum sum of a subarray ending at index i.
  • Iterate through the array, updating DP[i] to be the maximum of the current element and the sum of DP[i-1] and the current element.
  • Keep track of the maximum sum found in the DP array.

Below is the implementation of the above approach:

C++
// C++ program to find the maximum subarray sum using
// dynamic programming

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

// Function to find the maximum subarray sum
void maxSubArraySum(int a[], int size)
{
    // Initialize a DP array to store the maximum subarray
    // sum ending at each index
    vector<int> dp(size, 0);
    // The maximum sum ending at the first element is the
    // element itself
    dp[0] = a[0];
    // Initialize the answer with the first element
    int ans = dp[0];

    // Iterate through the array starting from the second
    // element
    for (int i = 1; i < size; i++) {
        // Update dp[i] to be the maximum of the current
        // element or the current element plus the previous
        // subarray sum
        dp[i] = max(a[i], a[i] + dp[i - 1]);
        // Update the answer to be the maximum of the
        // current answer or dp[i]
        ans = max(ans, dp[i]);
    }

    // Print the result
    cout << "Maximum subarray sum is " << ans << endl;
}

int main()
{
    // Array of integers
    int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 };
    int n = sizeof(a) / sizeof(a[0]);

    // Find and print the maximum subarray sum
    maxSubArraySum(a, n);

    return 0;
}

Output
Maximum subarray sum is 7

Time Complexity: O(N)
Auxiliary Space: O(N)


Next Article
Article Tags :
Practice Tags :

Similar Reads