![]() |
VOOZH | about |
An array is given, find the 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 2Input : 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 the Largest Sum Contiguous Subarray Problem.
The idea is to update starting index whenever the sum ending here becomes less than 0.
5
Time Complexity: O(N) where N is size of the input array. This is because a for loop is executed from 1 to size of the array.
Auxiliary Space: O(1) as no extra space has been taken.
Approach#2: Using Kadane’s algorithm
This approach implements Kadane’s algorithm to find the maximum subarray sum and returns the size of the subarray with the maximum sum.
Algorithm:
Below is the implementation of the approach:
5
Time Complexity: O(n), where n is the 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!