Minimum number of array elements from either ends required to be subtracted from X to reduce X to 0 | Python3 Program to implement the above approach ; Function to count the minimum number of operations required to reduce x to 0 ; If sum of the array is less than x ; Stores the count of operations ; Two pointers to traverse the array ; Reduce x by the sum of the entire array ; Iterate until l reaches the front of the array ; If sum of elements from the front exceeds x ; Shift towards left ; If sum exceeds 0 ; Reduce x by elements from the right ; If x is reduced to 0 ; Update the minimum count of operations required ; Driver Code
import math NEW_LINE def minOperations ( nums , x ) : NEW_LINE INDENT if sum ( nums ) < x : NEW_LINE INDENT return - 1 NEW_LINE DEDENT ans = math . inf NEW_LINE l , r = len ( nums ) - 1 , len ( nums ) NEW_LINE x -= sum ( nums ) NEW_LINE while l >= 0 : NEW_LINE INDENT if x <= 0 : NEW_LINE INDENT x += nums [ l ] NEW_LINE l -= 1 NEW_LINE DEDENT if x > 0 : NEW_LINE INDENT r -= 1 NEW_LINE x -= nums [ r ] NEW_LINE DEDENT if x == 0 : NEW_LINE INDENT ans = min ( ans , ( l + 1 ) + ( len ( nums ) - r ) ) NEW_LINE DEDENT DEDENT return ans if ans < math . inf else - 1 NEW_LINE DEDENT nums = [ 1 , 1 , 4 , 2 , 3 ] NEW_LINE x = 5 NEW_LINE print ( minOperations ( nums , x ) ) NEW_LINE