LeetCode 题解工作台
青蛙过河 II
给你一个下标从 0 开始的整数数组 stones ,数组中的元素 严格递增 ,表示一条河中石头的位置。 一只青蛙一开始在第一块石头上,它想到达最后一块石头,然后回到第一块石头。同时每块石头 至多 到达 一次。 一次跳跃的 长度 是青蛙跳跃前和跳跃后所在两块石头之间的距离。 更正式的,如果青蛙从 st…
3
题型
4
代码语言
3
相关题
当前训练重点
中等 · 二分·搜索·答案·空间
答案摘要
要使得跳跃过程中的每一步的最大跳跃长度最小,我们应该将跳跃过程切分成尽可能多的连续的步骤。通过观察,间隔跳跃可以获取最优解。 时间复杂度 ,空间复杂度 。其中 为数组 `stones` 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给你一个下标从 0 开始的整数数组 stones ,数组中的元素 严格递增 ,表示一条河中石头的位置。
一只青蛙一开始在第一块石头上,它想到达最后一块石头,然后回到第一块石头。同时每块石头 至多 到达 一次。
一次跳跃的 长度 是青蛙跳跃前和跳跃后所在两块石头之间的距离。
- 更正式的,如果青蛙从
stones[i]跳到stones[j],跳跃的长度为|stones[i] - stones[j]|。
一条路径的 代价 是这条路径里的 最大跳跃长度 。
请你返回这只青蛙的 最小代价 。
示例 1:

输入:stones = [0,2,5,6,7] 输出:5 解释:上图展示了一条最优路径。 这条路径的代价是 5 ,是这条路径中的最大跳跃长度。 无法得到一条代价小于 5 的路径,我们返回 5 。
示例 2:

输入:stones = [0,3,9] 输出:9 解释: 青蛙可以直接跳到最后一块石头,然后跳回第一块石头。 在这条路径中,每次跳跃长度都是 9 。所以路径代价是 max(9, 9) = 9 。 这是可行路径中的最小代价。
提示:
2 <= stones.length <= 1050 <= stones[i] <= 109stones[0] == 0stones中的元素严格递增。
解题思路
方法一:脑筋急转弯
要使得跳跃过程中的每一步的最大跳跃长度最小,我们应该将跳跃过程切分成尽可能多的连续的步骤。通过观察,间隔跳跃可以获取最优解。
时间复杂度 ,空间复杂度 。其中 为数组 stones 的长度。
class Solution:
def maxJump(self, stones: List[int]) -> int:
ans = stones[1] - stones[0]
for i in range(2, len(stones)):
ans = max(ans, stones[i] - stones[i - 2])
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n log D), where D is the range between the first and last stone, as binary search tests each jump length and each check traverses all stones. Space complexity is O(1) extra beyond the input array. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Focus on validating jump lengths efficiently rather than enumerating all paths.
- question_mark
Expect discussion on greedy verification within the binary search loop.
- question_mark
Look for handling of edge jumps and minimal maximum logic in your solution.
常见陷阱
外企场景- error
Assuming jumps can reuse stones, violating the problem constraint.
- error
Failing to correctly simulate the return path, leading to underestimated jumps.
- error
Mismanaging binary search bounds, which can skip the true minimal maximum.
进阶变体
外企场景- arrow_right_alt
Frog Jump with a single forward trip only, changing the binary search constraints.
- arrow_right_alt
Allow revisiting stones, which changes the greedy check strategy.
- arrow_right_alt
Frog Jump with variable energy limits, introducing dynamic programming options.