Maximum times X and Y can be reduced to near 0 using numbers A or B | Helper function to check if we can perform Mid number of moves let MAXN = 10000000 ; MAXN = 1e7 ; Remove atleast Mid * B from both X and Y ; If any value is negative return false . ; Calculate remaining values ; If val >= Mid then it is possible to perform this much moves ; else return false ; Initialize a variable to store the answer ; Fix the left and right range ; Binary Search over the answer ; Check for the middle value as the answer ; It is possible to perform this much moves ; Maximise the answer ; Return answer ; Driver Code ; Generalise that A >= B
function can ( Mid , X , Y , A , B ) { let p1 = X - Mid * B ; let p2 = Y - Mid * B ; if ( p1 < 0 p2 < 0 ) { return false ; } let k = A - B ; if ( k == 0 ) { return true ; } let val = Math . floor ( p1 / k ) + Math . floor ( p2 / k ) ; if ( val >= Mid ) { return true ; } return false ; } function maxPossibleMoves ( X , Y , A , B ) { let ans = 0 ; let L = 1 , R = MAXN ; while ( L <= R ) { let Mid = Math . floor ( ( L + R ) / 2 ) ; if ( can ( Mid , X , Y , A , B ) ) { L = Mid + 1 ; ans = Math . max ( ans , Mid ) ; } else { R = Mid - 1 ; } } return ans ; } let X = 10 , Y = 12 , A = 2 , B = 5 ; if ( A < B ) { let temp = A ; A = B ; B = temp ; } document . write ( maxPossibleMoves ( X , Y , A , B ) ) ;