Length of the smallest subarray with maximum possible sum | C ++ program for the above approach ; Function to find the minimum length of the subarray whose sum is maximum ; Stores the starting and the ending index of the resultant subarray ; Traverse the array until a non - zero element is encountered ; If the array contains only of 0 s ; Traverse the array in reverse until a non - zero element is encountered ; Return the resultant size of the subarray ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumSizeSubarray ( int arr [ ] , int N ) { int i = 0 , j = N - 1 ; while ( i < N and arr [ i ] == 0 ) { i ++ ; } if ( i == N ) return 1 ; while ( j >= 0 and arr [ j ] == 0 ) { j -- ; } return ( j - i + 1 ) ; } int main ( ) { int arr [ ] = { 0 , 2 , 0 , 0 , 12 , 0 , 0 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimumSizeSubarray ( arr , N ) ; return 0 ; }