Length of the smallest subarray with maximum possible sum | 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
function minimumSizeSubarray ( arr , N ) { let i = 0 , j = N - 1 ; while ( i < N && arr [ i ] == 0 ) { i ++ ; } if ( i == N ) return 1 ; while ( j >= 0 && arr [ j ] == 0 ) { j -- ; } return ( j - i + 1 ) ; } let arr = [ 0 , 2 , 0 , 0 , 12 , 0 , 0 , 0 ] ; let N = arr . length ; document . write ( minimumSizeSubarray ( arr , N ) ) ;