Frog Jump

Pattern: 1D DP

medium

The frog jumps 1 or 2 stones, paying the height difference each time. The cheapest way to stone i is the cheaper of coming from i - 1 or i - 2.

The problem

A frog starts on stone 0 and wants to reach the last stone, jumping 1 or 2 stones at a time. A jump from i to j costs |heights[i] - heights[j]|. Return the least total cost. [10, 20, 30, 10] gives 20.

Think first

  • Where could the last jump have started?
  • What did it cost to get there?
  • What is the cost of stone 0?

Hints

    Brute force, and why it fails

    Try every sequence of jumps: O(2ⁿ).

    The key insight

    The cheapest way to each stone only depends on the two stones before it.

    Dry run

    best0 10

    heights [10, 20, 30, 10]. best(0) = 0, best(1) = 10.

    Step 1 of 3

    The plan

    best(i) = min(best(i-1) + |h[i] - h[i-1]|, best(i-2) + |h[i] - h[i-2]|)
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    Two previous values are kept.

    Edge cases

    • One stone: 0.
    • Two stones: one jump.
    • Equal heights: 0.
    I've built my logic, show the code

    Java

    class Solution {
        public int frogJump(int[] heights) {
            int n = heights.length, prev2 = 0, prev = 0;   // best energy to reach stone i - 2 and i - 1
            for (int i = 1; i < n; i++) {
                int one = prev + Math.abs(heights[i] - heights[i - 1]);
                int two = i > 1 ? prev2 + Math.abs(heights[i] - heights[i - 2]) : Integer.MAX_VALUE;
                int cur = Math.min(one, two);       // the last jump was 1 or 2 stones
                prev2 = prev;
                prev = cur;
            }
            return prev;
        }
    }

    C++

    class Solution {
    public:
        int frogJump(vector<int>& heights) {
            int n = static_cast<int>(heights.size()), prev2 = 0, prev = 0;   // best energy to reach stone i - 2 and i - 1
            for (int i = 1; i < n; i++) {
                int one = prev + abs(heights[i] - heights[i - 1]);
                int two = i > 1 ? prev2 + abs(heights[i] - heights[i - 2]) : INT_MAX;
                int cur = min(one, two);            // the last jump was 1 or 2 stones
                prev2 = prev;
                prev = cur;
            }
            return prev;
        }
    };

    Python

    class Solution:
        def frogJump(self, heights: list[int]) -> int:
            prev2 = prev = 0                        # best energy to reach stone i - 2 and i - 1
            for i in range(1, len(heights)):
                one = prev + abs(heights[i] - heights[i - 1])
                two = prev2 + abs(heights[i] - heights[i - 2]) if i > 1 else float("inf")
                prev2, prev = prev, min(one, two)   # the last jump was 1 or 2 stones
            return prev

    Common mistakes

    • Forgetting i - 2 does not exist at i = 1.
    • Adding heights instead of differences.

    Similar problems