[LeetCode] Minimum Moves to Reach Target Score

2139. Minimum Moves to Reach Target Score

You are playing a game with integers. You start with the integer 1 and you want to reach the integer target.

In one move, you can either:

  • Increment the current integer by one (i.e., x = x + 1).
  • Double the current integer (i.e., x = 2 * x).

You can use the increment operation any number of times, however, you can only use the double operation at most maxDoubles times.

Given the two integers target and maxDoubles, return the minimum number of moves needed to reach target starting with 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int minMoves(int target, int maxDoubles) {
int res = 0;
while(target != 1) {
if(target & 1) target--;
else {
if(maxDoubles) {
target /= 2;
maxDoubles--;
} else return target - 1 + res;
}
res++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/03/PS/LeetCode/minimum-moves-to-reach-target-score/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.