Minimum array elements required to be subtracted from either end to reduce K to 0 | Function to find the length of longest subarray having sum K ; Stores the index of the prefix sum ; Traverse the given array ; Update sum ; If the subarray starts from index 0 ; Add the current prefix sum with index if it is not present in the map um ; Check if sum - K is present in Map um or not ; Update the maxLength ; Return the required maximum length ; Function to find the minimum removal of array elements required to reduce K to 0 ; Stores the sum of the array ; Traverse the array arr [ ] ; Update sum of the array ; Find maxLen ; If the subarray with sum doesn 't exist ; Otherwise , print the required maximum length ; Driver Code
function longestSubarray ( arr , N , K ) { let um = new Map ( ) ; let sum = 0 , maxLen = 0 ; for ( let i = 0 ; i < N ; i ++ ) { sum += arr [ i ] ; if ( sum == K ) maxLen = i + 1 ; if ( ! um . has ( sum ) ) um . set ( sum , i ) ; if ( um . has ( sum - K ) ) { if ( maxLen < ( i - um . get ( sum - K ) ) ) maxLen = i - um . get ( sum - K ) ; } } return maxLen ; } function minRequiredOperation ( arr , N , K ) { let TotalSum = 0 ; for ( let i = 0 ; i < N ; i ++ ) TotalSum += arr [ i ] ; let maxLen = longestSubarray ( arr , N , TotalSum - K ) ; if ( maxLen == - 1 ) { document . write ( - 1 ) ; } else document . write ( N - maxLen ) ; } let arr = [ 1 , 3 , 1 , 1 , 2 ] ; let K = 4 ; let N = arr . length minRequiredOperation ( arr , N , K ) ;