美文网首页
LeetCode 1033. Moving Stones Unt

LeetCode 1033. Moving Stones Unt

作者: LiNGYu_NiverSe | 来源:发表于2020-11-05 01:10 被阅读0次

Description
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 maximum number of moves that you could have made? Return the answer as an length 2 array: answer = [minimum_moves, maximum_moves]

Example 1:

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.

Example 2:

Input: a = 4, b = 3, c = 2
Output: [0,0]
Explanation: We cannot make any moves.

Example 3:

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

Note:

1 <= a <= 100
1 <= b <= 100
1 <= c <= 100
a != b, b != c, c != a

Solution:

class Solution:
    def numMovesStones(self, a: int, b: int, c: int) -> List[int]:
        x, y, z = sorted([a, b, c])
        if x + 1 == y == z - 1:
            min_steps = 0
        elif y - x > 2 and z - y > 2:
            min_steps = 2
        else:
            min_steps = 1
        max_steps = z - x - 2
        return [min_steps, max_steps]

Explanation:

First, let's look at the min_steps. If 3 points are all next to each other, the min_steps will be 0. If the space of either two of them is 1 (y-x > 2 or z-y > 2), we can move the 3rd one to fill the space, so the min_step will be 1. If two spaces are all greater than 1, then we have to move twice to end the game.

For max_step, we just need to move 1 step at a time(z- x), but keep in mind that both z and y themselves will consume 2 positions, so we need to minus 2 at the end (z-x-2) .

相关文章

网友评论

      本文标题:LeetCode 1033. Moving Stones Unt

      本文链接:https://www.haomeiwen.com/subject/mxznvktx.html