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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read