Count of decrement operations required to obtain K in N steps | 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 ; Given and N , K ; Function call
def isValid ( n , m , k ) : NEW_LINE INDENT step2 = n - m NEW_LINE cnt = ( step2 * ( step2 + 1 ) ) // 2 NEW_LINE if ( cnt - m == k ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( cnt - m > k ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT def countOfOperations ( n , k ) : NEW_LINE INDENT start = 0 NEW_LINE end = n NEW_LINE ok = 1 NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( start + end ) // 2 NEW_LINE temp = isValid ( n , mid , k ) NEW_LINE if ( temp == 0 ) : NEW_LINE INDENT ok = 0 NEW_LINE print ( mid ) NEW_LINE break NEW_LINE DEDENT elif ( temp == 1 ) : NEW_LINE INDENT start = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT DEDENT if ( ok ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT N = 5 NEW_LINE K = 4 NEW_LINE countOfOperations ( N , K ) NEW_LINE