Sponsored
Sponsored
Instead of moving from the startValue
to target
, consider reversing the operations. Start from the target
and attempt to reach the startValue
. If the target
is even, divide it by 2. If it is odd, add 1 to it. Continue until the target
is less than or equal to the startValue
. This allows you to efficiently compute the minimum steps by potentially making large reductions through division by 2.
Time Complexity: O(log n)
, where n
is the target due to halving operation.
Space Complexity: O(1)
as no extra space is used.
1public class BrokenCalculator {
2 public static int brokenCalc(int startValue, int target) {
3 int operations = 0;
4 while (target > startValue) {
5 operations++;
6 if (target % 2 == 1) {
7 target++;
8 } else {
9 target /= 2;
10 }
11 }
12 return operations + (startValue - target);
13 }
14
15 public static void main(String[] args) {
16 int startValue = 3, target = 10;
17 System.out.println(brokenCalc(startValue, target));
18 }
19}
This Java program executes the same logic: reducing the target with divide by 2 or plus 1 operations till it becomes less than or equal to startValue. Extra decrements are added if the adjusted target is still greater than startValue.
Using a greedy approach, always attempt the operation that brings the target closer to the startValue significantly, which is multiplication by 2 in the reverse. Only when all doubling possibilities are exhausted, should we use subtraction/addition operations.
Time Complexity: O(log n)
due to division operations.
Space Complexity: O(1)
.
1def
The Python script applies the greedy method to decrementally converge upon the startValue, being efficient with division when possible.