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
def longestSubarray ( arr , N , K ) : NEW_LINE INDENT um = { } NEW_LINE sum , maxLen = 0 , 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE if ( sum == K ) : NEW_LINE INDENT maxLen = i + 1 NEW_LINE DEDENT if ( sum not in um ) : NEW_LINE INDENT um [ sum ] = i NEW_LINE DEDENT if ( ( sum - K ) in um ) : NEW_LINE INDENT if ( maxLen < ( i - um [ sum - K ] ) ) : NEW_LINE INDENT maxLen = i - um [ sum - K ] NEW_LINE DEDENT DEDENT DEDENT return maxLen NEW_LINE DEDENT def minRequiredOperation ( arr , N , K ) : NEW_LINE INDENT TotalSum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT TotalSum += arr [ i ] NEW_LINE DEDENT maxLen = longestSubarray ( arr , N , TotalSum - K ) NEW_LINE if ( maxLen == - 1 ) : NEW_LINE INDENT print ( - 1 , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( N - maxLen , end = " " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 1 , 1 , 2 ] NEW_LINE K = 4 NEW_LINE N = len ( arr ) NEW_LINE minRequiredOperation ( arr , N , K ) NEW_LINE DEDENT