Moving Stones Until Consecutive

Three stones are on a number line at positions ab, and c.

Each turn, you pick up a stone at an endpoint (ie., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints.  Formally, let's say the stones are currently at positions x, y, z with x < y < z.  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.

The game ends when you cannot make any more moves, ie. the stones are in consecutive positions.

When the game ends, what is the minimum and the maximum number of moves that you could have made?  Return the answer as a length 2 array: answer = [minimum_moves, maximum_moves]

Example:

Input: a = 1, b = 2, c = 5
Output: [1,2]
Explanation: Move the stone from 5 to 3, or move the stone from 5 to 4 to 3.

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

vector<intnumMovesStones(int aint bint c)
{
    int x = min(amin(bc));
    int z = max(amax(bc));
    int y = a + b + c - x - z;

    //if all are consecutive
    if (x + 1 == y && y + 1 == z)
    {
        return {00};
    }

    //if two are consecutive
    if (x + 1 == y)
    {
        return {1z - y - 1};
    }

    //if two are consecutive
    if (y + 1 == z)
    {
        return {1y - x - 1};
    }

    //if no two are consecutive
    return {min(2min(z - y - 1y - x - 1)), z - x - 2};
}

int main()
{
    int a = 1b = 2c = 5;

    vector<intres = numMovesStones(abc);

    cout << res[0] << " " << res[1] << "\n";

    return 0;
}


No comments:

Post a Comment