MeetCode
Minimum steps to reach target (1 or 2)
C
C++
Computer Mathematics
CSS
DSA
HTML
Java
JavaScript
NodeJS
PHP
Programming Interview
Python
ReactJS
SQL
Run
Submit
Dark
Problem Statement
Solutions
Submissions
Minimum steps to reach target (1 or 2)
Hard
Java
Control Flow
17 views
Explanation
Complexity
Problem Statement
Task: you can add 1 or 2 each move. Return minimum moves to reach exactly n.
Input Format
An integer n.
Output Format
An integer: minimum number of moves to reach exactly n.
Example
Input
5
Output
3
Constraints
• n ≥ 0
• In one move, you can add 1 or 2
Concept Explanation
To minimize moves, we should add 2 whenever possible.
If n is odd, one extra move of +1 is needed.
Step-by-Step Explanation
1.Read integer n.
2.Initialize moves = 0.
3.While n > 0:
• If n >= 2:
• Subtract 2 from n.
• Else:
• Subtract 1 from n.
• Increment moves.
4.When n becomes 0, return moves.
Concept Explanation
To minimize moves, we should add 2 whenever possible.
If n is odd, one extra move of +1 is needed.
Step-by-Step Explanation
1.Read integer n.
2.Initialize moves = 0.
3.While n > 0:
• If n >= 2:
• Subtract 2 from n.
• Else:
• Subtract 1 from n.
• Increment moves.
4.When n becomes 0, return moves.
Input / Output Format
Input Format
An integer n.
Output Format
An integer: minimum number of moves to reach exactly n.
Constraints
• n ≥ 0
• In one move, you can add 1 or 2
Examples
Input:
5
Output:
3
Example Solution (Public)
Java
static int minMoves12(int n){return n/2 + (n%2);}
Official Solution Code
Wrap
Copy
static int minMoves12(int n){return n/2 + (n%2);}
Please
login
to submit solutions.
Editor
C
C++
Computer Mathematics
CSS
DSA
HTML
Java
JavaScript
NodeJS
PHP
Programming Interview
Python
ReactJS
SQL
Test Cases
Output
Submission Result
Input
5
Expected Output
3
Compile Output
Error
Output
Please
login
to submit solutions.