Frog Jump II - Problem

You are given a 0-indexed integer array stones sorted in strictly increasing order representing the positions of stones in a river.

A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone at most once.

The length of a jump is the absolute difference between the position of the stone the frog is currently on and the position of the stone to which the frog jumps.

More formally, if the frog is at stones[i] and is jumping to stones[j], the length of the jump is |stones[i] - stones[j]|.

The cost of a path is the maximum length of a jump among all jumps in the path.

Return the minimum cost of a path for the frog.

Input & Output

Example 1 — Basic Case
$ Input: stones = [0,2,5,6,7]
Output: 5
💡 Note: The optimal strategy uses alternating pattern. For path 0→2→6→7→5→0, jumps are [2,4,1,2,5] with maximum 5. For path 0→5→7→6→2→0, jumps are [5,2,1,4,2] with maximum 5. The minimum cost is 5.
Example 2 — Minimum Size
$ Input: stones = [0,10]
Output: 0
💡 Note: Only two stones, frog starts at first and needs to reach second then return. No intermediate jumps needed.
Example 3 — Three Stones
$ Input: stones = [0,3,9]
Output: 9
💡 Note: Path: 0→3→9→0. Jumps are [3,6,9]. The minimum maximum jump is 9.

Constraints

  • 2 ≤ stones.length ≤ 105
  • 0 ≤ stones[i] ≤ 109
  • stones[0] = 0
  • stones is sorted in strictly increasing order

Visualization

Tap to expand
Frog Jump II - Greedy Alternating Strategy INPUT River 0 2 5 6 7 stones array: 0 2 5 6 7 [0] [1] [2] [3] [4] Frog starts at stone 0 Must reach stone 7 Then return to stone 0 Each stone visited once! Goal: Minimize the maximum jump length ALGORITHM STEPS 1 Alternating Strategy Forward: skip every other Return: use skipped stones 2 Forward Path 0 --> 5 --> 7 Jumps: 5, 2 3 Return Path 7 --> 6 --> 2 --> 0 Jumps: 1, 4, 2 (or equiv) 4 Find Max Gap Check stones[i+2]-stones[i] for all valid i 0 2 5 6 7 Forward (blue) Return (green) FINAL RESULT Gap Calculations: i=0: stones[2]-stones[0] = 5 - 0 = 5 i=1: stones[3]-stones[1] = 6 - 2 = 4 i=2: stones[4]-stones[2] = 7 - 5 = 2 Wait! Optimal is 3! Better alternating: Fwd: 0-->2-->5-->7 (max 3) Ret: 7-->6-->0 (max 1,6) OUTPUT 3 OK Key Insight: The optimal strategy uses alternating stones: frog visits even-indexed stones going forward, odd-indexed stones returning. Maximum gap = max(stones[i+2] - stones[i]) for all valid i. This ensures each stone is used exactly once and minimizes the maximum jump distance. TutorialsPoint - Frog Jump II | Greedy - Alternating Strategy
Asked in
Google 15 Meta 12
12.8K Views
Medium Frequency
~25 min Avg. Time
456 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen