Minimum removal of elements from end of an array required to obtain sum K | Function to find the minimum number of elements required to be removed from the ends of an array to obtain a sum K ; Number of elements removed from the left and right ends of the array ; Sum of left and right subarrays ; No element is taken from left initially ; Start taking elements from right side ; ( left + 1 ) : Count of elements removed from the left ( N - right ) : Count of elements removed from the right ; If sum is greater than K ; If it is not possible to obtain sum K ; Driver code ; Given Array ; Given target sum
function minSizeArr ( A , N , K ) { let leftTaken = N , rightTaken = N ; let leftSum = 0 , rightSum = 0 ; for ( let left = - 1 ; left < N ; left ++ ) { if ( left != - 1 ) leftSum += A [ left ] ; rightSum = 0 ; for ( let right = N - 1 ; right > left ; right -- ) { rightSum += A [ right ] ; if ( leftSum + rightSum == K ) { if ( leftTaken + rightTaken > ( left + 1 ) + ( N - right ) ) { leftTaken = left + 1 ; rightTaken = N - right ; } break ; } if ( leftSum + rightSum > K ) break ; } } if ( leftTaken + rightTaken <= N ) { for ( let i = 0 ; i < leftTaken ; i ++ ) document . write ( A [ i ] + " " ) ; for ( let i = 0 ; i < rightTaken ; i ++ ) document . write ( A [ N - i - 1 ] + " " ) ; } else document . write ( - 1 ) ; } let N = 7 ; let A = [ 3 , 2 , 1 , 1 , 1 , 1 , 3 ] ; let K = 10 ; minSizeArr ( A , N , K ) ;