C++ Program for Size of The Subarray With Maximum Sum
Last Updated :
12 May, 2023
An array is given, find length of the subarray having maximum sum.
Examples :
Input : a[] = {1, -2, 1, 1, -2, 1}
Output : Length of the subarray is 2
Explanation: Subarray with consecutive elements
and maximum sum will be {1, 1}. So length is 2
Input : ar[] = { -2, -3, 4, -1, -2, 1, 5, -3 }
Output : Length of the subarray is 5
Explanation: Subarray with consecutive elements
and maximum sum will be {4, -1, -2, 1, 5}.
This problem is mainly a variation of Largest Sum Contiguous Subarray Problem.
The idea is to update starting index whenever sum ending here becomes less than 0.
C++
// C++ program to print length of the largest
// contiguous array sum
#include<bits/stdc++.h>
using namespace std;
int maxSubArraySum(int a[], int size)
{
int max_so_far = INT_MIN, max_ending_here = 0,
start =0, end = 0, s=0;
for (int i=0; i< size; i++ )
{
max_ending_here += a[i];
if (max_so_far < max_ending_here)
{
max_so_far = max_ending_here;
start = s;
end = i;
}
if (max_ending_here < 0)
{
max_ending_here = 0;
s = i + 1;
}
}
return (end - start + 1);
}
/*Driver program to test maxSubArraySum*/
int main()
{
int a[] = {-2, -3, 4, -1, -2, 1, 5, -3};
int n = sizeof(a)/sizeof(a[0]);
cout << maxSubArraySum(a, n);
return 0;
}
Time Complexity: O(N) where N is size of the input array. This is because a for loop is executing from 1 to size of the array.
Space Complexity: O(1) as no extra space has been taken.
Approach#2: Using Kadane’s algorithm
This approach implements the Kadane’s algorithm to find the maximum subarray sum and returns the size of the subarray with maximum sum.
Algorithm:
- Initialize max_sum, current_sum, start, end, max_start, and max_end to the first element of the array.
- Iterate through the array from the second element.
- If the current element is greater than the sum of the current element and current_sum, update start to the current index.
- Update current_sum as the maximum of the current element and the sum of current element and current_sum.
- If current_sum is greater than max_sum, update max_sum, end to the current index, and max_start and max_end to start and end respectively.
- Return max_end – max_start + 1 as the size of the subarray with maximum sum.
Below is the implementation of the approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the maximum subarray sum
int max_subarray_sum(vector<int>& a)
{
int n = a.size();
int max_sum = a[0];
int current_sum = a[0];
int start = 0;
int end = 0;
int max_start = 0;
int max_end = 0;
// Traverse the array
for (int i = 1; i < n; i++) {
// If the current element is greater than the sum so
// far plus the current element, then update the
// start index to the current index
if (a[i] > current_sum + a[i]) {
start = i;
}
// Update the current sum to be either the current
// element or the sum so far plus the current
// element
current_sum = max(a[i], current_sum + a[i]);
// If the current sum is greater than the maximum
// sum so far, then update the maximum sum and its
// start and end indices
if (current_sum > max_sum) {
max_sum = current_sum;
end = i;
max_start = start;
max_end = end;
}
}
// Return the length of the maximum subarray
return max_end - max_start + 1;
}
// Driver's code
int main()
{
vector<int> a{ -2, -3, 4, -1, -2, 1, 5, -3 };
cout << max_subarray_sum(a) << endl;
return 0;
}
Time Complexity: O(n), where n is length of array
Auxiliary Space: O(1)
Note: The above code assumes that there is at least one positive element in the array. If all the elements are negative, the code needs to be modified to return the maximum element in the array.
Please refer complete article on Size of The Subarray With Maximum Sum for more details!
Similar Reads
C++ Program for Number of pairs with maximum sum Given an array arr[], count number of pairs arr[i], arr[j] such that arr[i] + arr[j] is maximum and i Example : Input : arr[] = {1, 1, 1, 2, 2, 2} Output : 3 Explanation: The maximum possible pair sum where i Method 1 (Naive)Â Traverse a loop i from 0 to n, i.e length of the array and another loop j
3 min read
C++ Program For Finding Subarray With Given Sum - Set 1 (Nonnegative Numbers) Given an unsorted array of non-negative integers, find a continuous subarray that adds to a given number. Examples : Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33 Output: Sum found between indexes 2 and 4 Sum of elements between indices 2 and 4 is 20 + 3 + 10 = 33 Input: arr[] = {1, 4, 0, 0, 3, 10,
5 min read
C++ Program to Find the K-th Largest Sum Contiguous Subarray Given an array of integers. Write a program to find the K-th largest sum of contiguous subarray within the array of numbers which has negative and positive numbers. Examples:Â Input: a[] = {20, -5, -1} k = 3 Output: 14 Explanation: All sum of contiguous subarrays are (20, 15, 14, -5, -6, -1) so the
3 min read
Maximum length of subarray such that sum of the subarray is even Given an array of N elements. The task is to find the length of the longest subarray such that sum of the subarray is even.Examples: Input : N = 6, arr[] = {1, 2, 3, 2, 1, 4}Output : 5Explanation: In the example the subarray in range [2, 6] has sum 12 which is even, so the length is 5.Input : N = 4,
11 min read
Sum of Max of Subarrays Given an array arr[], the task is to find the sum of the maximum elements of every possible non-empty sub-arrays of the given array arr[].Examples: Input: arr[] = [1, 3, 2]Output: 15Explanation: All possible non-empty subarrays of [1, 3, 2] are {1}, {3}, {2}, {1, 3}, {3, 2} and {1, 3, 2}. The maximu
12 min read
Longest unique subarray of an Array with maximum sum in another Array Given two arrays X[] and Y[] of size N, the task is to find the longest subarray in X[] containing only unique values such that a subarray with similar indices in Y[] should have a maximum sum. The value of array elements is in the range [0, 1000]. Examples: Input: N = 5, X[] = {0, 1, 2, 0, 2}, Y[]
10 min read
Maximum Sum SubArray using Divide and Conquer | Set 2 Given an array arr[] of integers, the task is to find the maximum sum sub-array among all the possible sub-arrays.Examples: Input: arr[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4} Output: 6 {4, -1, 2, 1} is the required sub-array.Input: arr[] = {2, 2, -2} Output: 4 Approach: Till now we are only aware of Kad
13 min read
C++ Program for Queries to find maximum sum contiguous subarrays of given length in a rotating array Given an array arr[] of N integers and Q queries of the form {X, Y} of the following two types: If X = 1, rotate the given array to the left by Y positions.If X = 2, print the maximum sum subarray of length Y in the current state of the array. Examples:Â Input: N = 5, arr[] = {1, 2, 3, 4, 5}, Q = 2,
5 min read
Maximum length sub-array which satisfies the given conditions Given an array arr[] of N integers, the task is to find the maximum length of any sub-array of arr[] which satisfies one of the given conditions: The subarray is strictly increasing.The subarray is strictly decreasing.The subarray is first strictly increasing then strictly decreasing. Examples: Inpu
9 min read
Length of longest subarray for each index in Array where element at that index is largest Given an array arr[] of size N, the task is to calculate, for i(0<=i<N), the maximum length of a subarray containing arr[i], where arr[i] is the maximum element. Example: Input : arr[ ] = {62, 97, 49, 59, 54, 92, 21}, N=7Output: 1 7 1 3 1 5 1Explanation: The maximum length of subarray in which
15 min read