Given an array arr[] consisting of N non-negative integers, the task is to find the minimum length of the subarray whose sum is maximum.
Example:
Input: arr[] = {0, 2, 0, 0, 12, 0, 0, 0}
Output: 4
Explanation: The sum of the subarray {2, 0, 0, 12} = 2 + 0 + 0 + 12 = 14, which is maximum sum possible and the length of the subarray is 4, which is minimum.Input: arr[] = {2, 0, 0}
Output: 1
Naive Approach: The simplest approach to solve the given problem is to generate all possible subarray of the given array and print the length of that subarray whose sum is the sum of the array having minimum length among all possible subarray of the same sum.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized by using the fact that all elements are non-negative so the maximum sum of the subarray is the sum of the array itself. Therefore, the idea is to exclude the trailing 0s from either end of the array to minimize the resultant subarray length with maximum sum. Follow the steps below to solve the problem:
- Initialize two variables, say i as 0 and j as (N – 1) that store the starting and the ending index of the resultant subarray.
- Traverse the given array from the front until a positive element is encountered and simultaneously increment the value of i.
- If the value of i is N, then print the maximum length of the resultant subarray as 1 because it contains all elements as 0. Otherwise, traverse the given array from the end until a positive element is encountered and simultaneously decrement the value of j.
- After completing the above steps, print the value of (j – i + 1) as the resultant subarray.
Below is the implementation of the above approach:
C++
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer Geeks Classes Live
Original page link
Best Cool Tech Gadgets
Top favorite technology gadgets
0 comments:
Post a Comment