Problem Description
You are given two non-negative integers num1
and num2
. In one operation, if num1 >= num2
, you must subtract num2
from num1
, otherwise subtract num1
from num2
. Return the number of operations required to make either num1 = 0
or num2 = 0
.
Key Insights
- The operations are based on comparing
num1
andnum2
. - Each operation reduces one of the numbers, leading to a possible optimization.
- The problem can be viewed as repeatedly reducing the larger number by the smaller number.
- If both numbers are equal, only one operation is needed to make one of them zero.
Space and Time Complexity
Time Complexity: O(max(num1, num2))
Space Complexity: O(1)
Solution
The approach involves repeatedly comparing the two numbers and performing subtraction based on their values. Instead of simulating each operation, we can optimize by directly calculating how many times we can subtract the smaller number from the larger one. This can be done using integer division, which allows us to count operations more efficiently. The algorithm continues until at least one of the numbers reaches zero.