250. Minimum Knight Moves on Infinite Chessboard
Minimum Knight Moves on Infinite Chessboard
A knight is placed at coordinate [0, 0] on an infinite chessboard. The board has no boundary, so coordinates may be positive or negative.
In a single move, the knight travels two squares along one axis and one square along the other axis. Given a target coordinate [x, y], return the fewest moves needed for the knight to reach that target.
The target is always reachable.

Method Signature

int minKnightMoves(int x, int y)
  • x is the x-coordinate of the target square.
  • y is the y-coordinate of the target square.
  • The method returns the minimum number of knight moves required to go from [0, 0] to [x, y].

Rules

  • Each move must be a valid knight move.
  • A valid move changes the position by 2 along one axis and 1 along the other axis.
  • The knight may move to any positive or negative coordinate because the board is infinite.
  • The output is deterministic because only the minimum number of moves is returned.

Constraints

  • -300 ≤ x ≤ 300
  • -300 ≤ y ≤ 300
  • |x| + |y| ≤ 300

Examples

Example 1

Input: minKnightMoves(x = -1, y = 2)
Output: 1
Explanation: The knight can directly move from [0, 0] to [-1, 2] in one move.

Example 2

Input: minKnightMoves(x = 2, y = 0)
Output: 2
Explanation: One shortest path is [0, 0] -> [1, 2] -> [2, 0].

Example 3

Input: minKnightMoves(x = 4, y = 0)
Output: 2
Explanation: One shortest path is [0, 0] -> [2, 1] -> [4, 0].


Please use Laptop/Desktop or any other large screen to add/edit code.