Minimum number of array elements from either ends required to be subtracted from X to reduce X to 0 | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; static int minOperations ( int nums [ ] , int N , int x ) { int sum = 0 ; for ( int i = 0 ; i < x ; i ++ ) sum += nums [ i ] ; if ( sum < x ) return -1 ; int ans = INT_MAX ; int l = N - 1 , r = N ; 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 = min ( ans , ( l + 1 ) + ( N - r ) ) ; } } if ( ans < INT_MAX ) return ans ; else return -1 ; } int main ( ) { int nums [ ] = { 1 , 1 , 4 , 2 , 3 } ; int N = sizeof ( nums ) / sizeof ( nums [ 0 ] ) ; int x = 5 ; cout << minOperations ( nums , N , x ) ; return 0 ; }