
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.
1#include <iostream>
2using namespace std;
3
4int brokenCalc(int startValue, int target) {
5 int operations = 0;
6 while (target > startValue) {
7 operations++;
8 if (target % 2 == 1) {
9 target++;
10 } else {
11 target /= 2;
12 }
13 }
14 return operations + (startValue - target);
15}
16
17int main() {
18 int startValue = 3, target = 10;
19 cout << brokenCalc(startValue, target) << endl;
20 return 0;
21}This C++ solution mirrors the C implementation. It reduces the target until it's no larger than the startValue using reverse operations, increasing the step count with each operation.
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).
1#
This C solution looks at the current relation between target and startValue, opting to expedite reduction using division when possible, and slow down with addition or subtraction when necessary.