Three stones are on a number line at positions a
, b
, 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<int> numMovesStones(int a, int b, int c){int x = min(a, min(b, c));int z = max(a, max(b, c));int y = a + b + c - x - z;//if all are consecutiveif (x + 1 == y && y + 1 == z){return {0, 0};}//if two are consecutiveif (x + 1 == y){return {1, z - y - 1};}//if two are consecutiveif (y + 1 == z){return {1, y - x - 1};}//if no two are consecutivereturn {min(2, min(z - y - 1, y - x - 1)), z - x - 2};}int main(){int a = 1, b = 2, c = 5;vector<int> res = numMovesStones(a, b, c);cout << res[0] << " " << res[1] << "\n";return 0;}
No comments:
Post a Comment