|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | + |
| 5 | +/** |
| 6 | + * 1033. Moving Stones Until Consecutive |
| 7 | + * |
| 8 | + * Three stones are on a number line at positions a, b, and c. |
| 9 | + * |
| 10 | + * Each turn, you pick up a stone at an endpoint (ie., either the lowest or highest position stone), |
| 11 | + * and move it to an unoccupied position between those endpoints. |
| 12 | + * Formally, let's say the stones are currently at positions x, y, z with x < y < z. |
| 13 | + * You pick up the stone at either position x or position z, and move that stone to an integer position k, with x < k < z and k != y. |
| 14 | + * |
| 15 | + * The game ends when you cannot make any more moves, ie. the stones are in consecutive positions. |
| 16 | + * |
| 17 | + * When the game ends, what is the minimum and maximum number of moves that you could have made? |
| 18 | + * Return the answer as an length 2 array: answer = [minimum_moves, maximum_moves] |
| 19 | + * |
| 20 | + * Note: |
| 21 | + * * 1 <= a <= 100 |
| 22 | + * * 1 <= b <= 100 |
| 23 | + * * 1 <= c <= 100 |
| 24 | + * * a != b, b != c, c != a |
| 25 | + */ |
| 26 | + |
| 27 | +public class _1033 { |
| 28 | + public static class Solution1 { |
| 29 | + private int minMoves(int x, int y, int z) { |
| 30 | + // already consecutive integers, nothing to be done |
| 31 | + if (x + 1 == y && y + 1 == z) { |
| 32 | + return 0; |
| 33 | + } |
| 34 | + // one of the following (sample) cases: |
| 35 | + // 1, 2, 8 (8 -> 3) |
| 36 | + // 1, 7, 8 (1 -> 6) |
| 37 | + // 1, 3, 8 (8 -> 2) |
| 38 | + // 1, 6, 8 (1 -> 7) |
| 39 | + if (y - x <= 2 || z - y <= 2) { |
| 40 | + return 1; |
| 41 | + } |
| 42 | + |
| 43 | + // move z to y + 1, x to y - 1 |
| 44 | + return 2; |
| 45 | + } |
| 46 | + |
| 47 | + private int maxMoves(int x, int y, int z) { |
| 48 | + return z - x - 2; |
| 49 | + } |
| 50 | + |
| 51 | + public int[] numMovesStones(int a, int b, int c) { |
| 52 | + int[] t = {a, b, c}; |
| 53 | + Arrays.sort(t); |
| 54 | + |
| 55 | + int min = minMoves(t[0], t[1], t[2]); |
| 56 | + int max = maxMoves(t[0], t[1], t[2]); |
| 57 | + |
| 58 | + return new int[]{min, max}; |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments