Minimum steps to reach target (1 or 2)

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

5
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

static int minMoves12(int n){return n/2 + (n%2);}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.