一.问题描述
Three stones are on a number line at positions a
, b
, 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 <= a <= 100
1 <= b <= 100
1 <= c <= 100
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]