Minimum removal of elements from end of an array required to obtain sum K | Function to find the smallest array that can be removed from the ends of an array to obtain sum K ; Sum of complete array ; If given number is greater than sum of the array ; If number is equal to the sum of array ; tar is sum of middle subarray ; Find the longest subarray with sum equal to tar ; If there is no subarray with sum equal to tar ; Driver Code ; Given Array ; Given target sum
function minSizeArr ( A , N , K ) { var sum = 0 ; var i ; for ( i = 0 ; i < N ; i ++ ) sum += A [ i ] ; if ( K > sum ) { cout << - 1 ; return ; } if ( K == sum ) { for ( i = 0 ; i < N ; i ++ ) { document . write ( A [ i ] + ' ' ) ; } return ; } var tar = sum - K ; var um = new Map ( ) ; um [ 0 ] = - 1 ; var left , right ; var cur = 0 , maxi = - 1 ; for ( i = 0 ; i < N ; i ++ ) { cur += A [ i ] ; if ( um . has ( cur - tar ) && i - um . get ( cur - tar ) > maxi ) { maxi = i - um . get ( cur - tar ) ; right = i ; left = um . get ( cur - tar ) ; } if ( ! um . has ( cur ) ) um . set ( cur , i ) ; } if ( maxi == - 1 ) cout << - 1 ; else { for ( i = 0 ; i <= left ; i ++ ) document . write ( A [ i ] + ' ' ) ; for ( i = 0 ; i < right ; i ++ ) document . write ( A [ N - i - 1 ] + ' ' ) ; } } var N = 7 ; var A = [ 3 , 2 , 1 , 1 , 1 , 1 , 3 ] ; var K = 10 ; minSizeArr ( A , N , K ) ;