Count the number of operations required to reduce the given number | Java 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
class GFG { static int operations ( int op [ ] , int n , int k ) { int i , count = 0 ; int nVal = 0 ; int min = Integer . MAX_VALUE ; for ( i = 0 ; i < n ; i ++ ) { nVal += op [ i ] ; min = Math . min ( min , nVal ) ; if ( ( k + nVal ) <= 0 ) return ( i + 1 ) ; } if ( nVal >= 0 ) return - 1 ; int times = ( k - Math . abs ( min ) ) / Math . abs ( nVal ) ; k = ( k - ( times * Math . 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 ; } public static void main ( String [ ] args ) { int op [ ] = { - 60 , 65 , - 1 , 14 , - 25 } ; int n = op . length ; int k = 100000 ; System . out . print ( operations ( op , n , k ) ) ; } }