Count the number of operations required to reduce the given number | C ++ implementation of the approach ; To store the normalized value of all the operations ; Minimum possible value for a series of operations ; If k can be reduced with first ( i + 1 ) operations ; Impossible to reduce k ; Number of times all the operations can be performed on k without reducing it to <= 0 ; Perform operations ; Final check ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int operations ( int op [ ] , int n , int k ) { int i , count = 0 ; int nVal = 0 ; int minimum = INT_MAX ; for ( i = 0 ; i < n ; i ++ ) { nVal += op [ i ] ; minimum = min ( minimum , nVal ) ; if ( ( k + nVal ) <= 0 ) return ( i + 1 ) ; } if ( nVal >= 0 ) return -1 ; int times = ( k - abs ( minimum ) ) / abs ( nVal ) ; k = ( k - ( times * abs ( nVal ) ) ) ; count = ( times * n ) ; while ( k > 0 ) { for ( i = 0 ; i < n ; i ++ ) { k = k + op [ i ] ; count ++ ; if ( k <= 0 ) break ; } } return count ; } int main ( ) { int op [ ] = { -60 , 65 , -1 , 14 , -25 } ; int n = sizeof ( op ) / sizeof ( op [ 0 ] ) ; int k = 100000 ; cout << operations ( op , n , k ) << endl ; }