VOOZH about

URL: https://www.geeksforgeeks.org/dsa/size-subarray-maximum-sum/

⇱ Size of The Subarray With Maximum Sum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Size of The Subarray With Maximum Sum

Last Updated : 11 Jul, 2025

Given an array arr[] of size N, the task is to 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 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}. 

Method 1: This problem is mainly a variation of Largest Sum Contiguous Subarray Problem
The idea is to update starting index whenever the sum ending here becomes less than 0.

Below is the implementation of the above approach:


Output : 
5

 

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

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

1. Initialize max_sum, current_sum, start, end, max_start, and max_end to the first element of the array.
2. Iterate through the array from the second element.
3. If the current element is greater than the sum of the current element and current_sum, update start to the current index.
4. Update current_sum as the maximum of the current element and the sum of current element and current_sum.
5. 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.
6. Return max_end - max_start + 1 as the size of the subarray with maximum sum.


Output
5

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.

Comment
Article Tags:
Article Tags: