Frog Jump
Solve this ProblemTest Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
1 ≤ heights.length ≤ 30 - ◆
0 ≤ heights[i] ≤ 1000
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Brute Force — Recursive Without Memoization
BruteWork backward from the last stair: the cheapest way to reach stair i is whichever is smaller — the cheapest way to reach stair i-1 plus the cost of a one-step jump from there, or the cheapest way to reach stair i-2 plus the cost of a two-step jump from there (when i-2 is a valid stair at all). Stair 0 costs nothing to "reach" since the frog starts there. Asking this question starting from the very last stair and letting it recurse down to stair 0 answers the whole problem, but the same stair's cheapest cost gets recomputed every time a different later stair happens to ask for it again.
O(2^n)O(n)1class Solution {
2 private int[] h;
3
4 public int frogJump(int[] heights) {
5 this.h = heights;
6 return solve(heights.length - 1);
7 }
8
9 private int solve(int i) {
10 if (i == 0) return 0;
11 int oneStep = solve(i - 1) + Math.abs(h[i] - h[i - 1]);
12 if (i == 1) return oneStep;
13 int twoStep = solve(i - 2) + Math.abs(h[i] - h[i - 2]);
14 return Math.min(oneStep, twoStep);
15 }
16}Optimal — Bottom-Up 1D DP
OptimalLet dp[i] hold the cheapest total cost to reach stair i from stair 0. dp[0] is 0 (the frog starts there for free), and dp[1] can only be reached by a one-step jump from stair 0. From stair 2 onward, dp[i] is the smaller of two options computed from already-filled entries: dp[i-1] plus a one-step jump, or dp[i-2] plus a two-step jump. Filling the table from the bottom up means every option is always based on costs that were already finalized earlier in the pass, and the answer is simply whatever ends up in the last slot.
O(n)O(n)1class Solution {
2 public int frogJump(int[] heights) {
3 int n = heights.length;
4 if (n <= 1) return 0;
5 int[] dp = new int[n];
6 dp[1] = Math.abs(heights[1] - heights[0]);
7 for (int i = 2; i < n; i++) {
8 int oneStep = dp[i - 1] + Math.abs(heights[i] - heights[i - 1]);
9 int twoStep = dp[i - 2] + Math.abs(heights[i] - heights[i - 2]);
10 dp[i] = Math.min(oneStep, twoStep);
11 }
12 return dp[n - 1];
13 }
14}