Maximum Subarray Sum in C++
Last Updated :
26 Jul, 2024
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.
Largest Sum Contiguous subarray Approaches to Find Maximum Subarray Sum in C++
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;
}
OutputMaximum Subarray Sum is 6
Time Complexity: O(N^2)
Auxiliary Space: O(1)
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.
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;
}
OutputMaximum Subarray Sum is 6
Time Complexity: O(N)
Auxiliary Space: O(1)
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;
}
OutputMaximum contiguous sum is 7
Starting index 2
Ending index 6
Time Complexity: O(N)
Auxiliary Space: O(1)
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;
}
OutputMaximum subarray sum is 7
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Maximum Product Subarray in C++
In this article, we will learn how to find the maximum product of a contiguous subarray within a given array of integers. This problem is a variation of the classic "Maximum Subarray Sum" problem and presents an additional challenge because it involves both positive and negative numbers in an array.
7 min read
CSES Solutions - Maximum Subarray Sum II
Given an array arr[] of N integers, your task is to find the maximum sum of values in a contiguous subarray with length between A and B. Examples: Input: N = 8, A = 1, B = 2, arr[] = {-1, 3, -2, 5, 3, -5, 2, 2}Output: 8Explanation: The subarray with maximum sum is {5, 3}, the length between 1 and 2,
12 min read
CSES Solutions - Maximum Subarray Sum
Given an array arr[] of N integers, your task is to find the maximum sum of values in a contiguous, nonempty subarray. Examples: Input: N = 8, arr[] = {-1, 3, -2, 5, 3, -5, 2, 2}Output: 9Explanation: The subarray with maximum sum is {3, -2, 5, 3} with sum = 3 - 2 + 5 + 3 = 9. Input: N = 6, arr[] = {
5 min read
Maximum circular subarray sum of size K
Given an array arr of size N and an integer K, the task is to find the maximum sum subarray of size k among all contiguous sub-array (considering circular subarray also). Examples: Input: arr = {18, 4, 3, 4, 5, 6, 7, 8, 2, 10}, k = 3 Output: max circular sum = 32 start index = 9 end index = 1 Explan
6 min read
Largest Sum Contiguous Subarray in C
In this article, we will learn how to find the maximum sum of a contiguous subarray for a given array that contains both positive and negative integers in C language. Example: Input:Â arr = {-2, -3, 4, -1, -2, 1, 5, -3}Output:Â 7Explanation:Â The subarray {4,-1, -2, 1, 5} has the largest sum 7. Table o
4 min read
Maximum Subarray Sum after inverting at most two elements
Given an array arr[] of integer elements, the task is to find maximum possible sub-array sum after changing the signs of at most two elements.Examples: Input: arr[] = {-5, 3, 2, 7, -8, 3, 7, -9, 10, 12, -6} Output: 61 We can get 61 from index 0 to 10 by changing the sign of elements at 4th and 7th i
11 min read
std::max in C++
The std::max() is the built-in function in C++ used for finding the maximum among two or more elements passed to it as arguments. It is defined inside <algorithm> header file. In this article, we will learn how to use std::max() function in C++. The std::max() can be used in the following ways
3 min read
Maximum size subset with given sum using Backtracking
Given an array arr[] consisting of N integers and an integer K, the task is to find the length of the longest subsequence with a sum equal to K.Examples: Input: arr[] = {-4, -2, -2, -1, 6}, K = 0 Output: 3 Explanation: The longest subsequence is of length 3 which is {-4, -2, 6} having sum 0.Input: a
9 min read
array::max_size() in C++ STL
Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::max_size() This function returns the maximum number of elements that the array container can contain. In c
1 min read
Maximum number of elements that can be taken
Given an array of N integers. Each i'th element increases your sum by a[i], where a[i] can be negative which may decrease your sum. You start with sum=0 and iterate the array from left to right. at each index, you may add the element to your sum or not Your task is to add the maximum number of eleme
7 min read