leetcode 1033. Moving Stones Until Consecutive 解法 python

本文解析了一种基于石头位置的策略游戏,探讨了将三颗石头移动至连续位置所需的最少和最多步数。通过分析不同初始位置,得出最小移动步数为0至2步,最大步数等于两边界石头间距离减2。源代码使用Python实现,适用于LeetCode算法题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.问题描述

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

Each turn, 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 stone from 5 to 4 then to 3, or we can move it directly to 3.

Example 2:

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

 

Note:

  1. 1 <= a <= 100
  2. 1 <= b <= 100
  3. 1 <= c <= 100
  4. a != b, b != c, c != a

二.解题思路

核心是对最小和最大step情况的判断

对于最小来说,步数范围是0~2,0的情况就是三个直接在一起,1的情况就是三个中有两个相邻,或者有两个之间的距离是1,可以把另一个直接插在中间。2的话就是不是上诉情况,要把两个石头分别移到中间石头的两边。

最大step就很简单了,固定的,因为石头只能在两个边界之间走,所以最大就是两个边界之间能走的都走完。因为就是一次一步步走嘛,并且边界的石头如果越过了中间那块石头,那他就从边界的石头变成了中间的石头,之后边界的石头还是得一步步走。意思就是不管什么走法,最大的走法他们都会把两个边界之间能走的地方走满,(想证明的直接用反证法,比这种情况的maxstep还大的意思就是有某个位置被走了1步以上,想想看有什么情况哪个位置才能走一步以上)。所以最大就是两个边界值相减减去2,减2是因为他们仨连在一起之后,移动的那俩还得占两个坑。

更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我

欢迎大家一起套路一起刷题一起ac

三.源码

class Solution:
    def numMovesStones(self, a: int, b: int, c: int) -> List[int]:
        listtmp=[a,b,c]
        listtmp.sort()
        a,b,c=listtmp
        if b-a==1 and c-b ==1:
            return [0,0]
        minstep=2
        if b-a==1 or c-b==1 or c-b==2 or b-a==2:
            minstep-=1
        maxstep=c-a
        maxstep-=2
        return [minstep,maxstep]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值