Minimum number of array elements from either ends required to be subtracted from X to reduce X to 0 | 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 poleters 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
function minOperations ( nums , x ) { let sum = 0 ; for ( let i = 0 ; i < x ; i ++ ) sum += nums [ i ] ; if ( sum < x ) return - 1 ; let ans = Number . MAX_VALUE ; let l = nums . length - 1 , r = nums . length ; x -= sum ; while ( l >= 0 ) { if ( x <= 0 ) { x += nums [ l ] ; l -= 1 ; } if ( x > 0 ) { r -= 1 ; x -= nums [ r ] ; } if ( x == 0 ) { ans = Math . min ( ans , ( l + 1 ) + ( nums . length - r ) ) ; } } if ( ans < Number . MAX_VALUE ) return ans ; else return - 1 ; } let nums = [ 1 , 1 , 4 , 2 , 3 ] ; let x = 5 ; document . write ( minOperations ( nums , x ) ) ;