Count the number of operations required to reduce the given number | PHP 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
< ? php function operations ( $ op , $ n , $ k ) { $ count = 0 ; $ nVal = 0 ; $ minimum = PHP_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 ; $ times = round ( ( $ 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 ; } $ op = array ( -60 , 65 , -1 , 14 , -25 ) ; $ n = sizeof ( $ op ) ; $ k = 100000 ; echo operations ( $ op , $ n , $ k ) ; ? >