Count of decrement operations required to obtain K in N steps | Java program for the above approach ; Function to check whether m number of steps of type 1 are valid or not ; If m and n are the count of operations of type 1 and type 2 respectively , then n - m operations are performed ; Find the value of S after step 2 ; If m steps of type 1 is valid ; Function to find the number of operations of type 1 required ; Iterate over the range ; Find the value of mid ; Check if m steps of type 1 are valid or not ; If mid is the valid number of steps ; If no valid number of steps exist ; Driver Code ; Given and N , K ; Function call
import java . util . * ; class GFG { static int isValid ( int n , int m , int k ) { int step2 = n - m ; int cnt = ( step2 * ( step2 + 1 ) ) / 2 ; if ( cnt - m == k ) return 0 ; if ( cnt - m > k ) return 1 ; return - 1 ; } static void countOfOperations ( int n , int k ) { int start = 0 , end = n ; boolean ok = true ; while ( start <= end ) { int mid = ( start + end ) / 2 ; int temp = isValid ( n , mid , k ) ; if ( temp == 0 ) { ok = false ; System . out . print ( mid ) ; break ; } else if ( temp == 1 ) { start = mid + 1 ; } else { end = mid - 1 ; } } if ( ok ) System . out . print ( " - 1" ) ; } public static void main ( String [ ] args ) { int N = 5 , K = 4 ; countOfOperations ( N , K ) ; } }