Input: target =19, maxDoubles =2Output: 7Explanation: Initially, x =1Increment 3 times so x =4Double once so x =8Increment once so x =9Double again so x =18Increment once so x =19
Input: target =10, maxDoubles =4Output: 4Explanation:**** Initially, x =1Increment once so x =2Double once so x =4Increment once so x =5Double again so x =10
To minimize moves, we should use the double operation as much as possible, but only when it helps. Instead of simulating from 1 to target, we work backwards from target to 1, greedily halving when possible and decrementing otherwise.
classSolution {
publicintminMoves(int target, int maxDoubles) {
int ans = 0;
while (target > 1 && maxDoubles > 0) {
if (target % 2 == 0) {
target /= 2;
maxDoubles--;
} else {
target--;
}
ans++;
}
return ans + (target - 1);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funminMoves(target: Int, maxDoubles: Int): Int {
var t = target
var d = maxDoubles
var ans = 0while (t > 1&& d > 0) {
if (t % 2==0) {
t /=2 d-- } else {
t-- }
ans++ }
return ans + (t - 1)
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defminMoves(self, target: int, maxDoubles: int) -> int:
ans: int =0while target >1and maxDoubles >0:
if target %2==0:
target //=2 maxDoubles -=1else:
target -=1 ans +=1return ans + (target -1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnmin_moves(target: i32, max_doubles: i32) -> i32 {
letmut t = target;
letmut d = max_doubles;
letmut ans =0;
while t >1&& d >0 {
if t %2==0 {
t /=2;
d -=1;
} else {
t -=1;
}
ans +=1;
}
ans + (t -1)
}
}