Count of decrement operations required to obtain K in N steps | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; 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 ; } void countOfOperations ( int n , int k ) { int start = 0 , end = n ; bool ok = 1 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; int temp = isValid ( n , mid , k ) ; if ( temp == 0 ) { ok = 0 ; cout << mid ; break ; } else if ( temp == 1 ) { start = mid + 1 ; } else { end = mid - 1 ; } } if ( ok ) cout << " - 1" ; } int main ( ) { int N = 5 , K = 4 ; countOfOperations ( N , K ) ; return 0 ; }