Frog Jump

Dynamic Programming 1D DP Medium

A frog wants to climb a staircase with n steps. Given an integer array heights, where heights[i] contains the height of the ith step.


To jump from the ith step to the jth step, the frog requires abs(heights[i] - heights[j]) energy, where abs() denotes the absolute difference. The frog can jump from any step either one or two steps, provided it exists. Return the minimum amount of energy required by the frog to go from the 0th step to the (n-1)th step.

Examples:

Input: heights = [2, 1, 3, 5, 4]

Output: 2

Explanation: One possible route can be,

0th step -> 2nd Step = abs(2 - 3) = 1

2nd step -> 4th step = abs(3 - 4) = 1

Total = 1 + 1 = 2.

Input: heights = [7, 5, 1, 2, 6]

Output: 9

Explanation: One possible route can be,

0th step -> 1st Step = abs(7 - 5) = 2

1st step -> 3rd step = abs(5 - 2) = 3

3rd step -> 4th step = abs(2 - 6) = 4

Total = 2 + 3 + 4 = 9.

Input: nums = [3, 10, 3, 11, 3]

Constraints

  • 1 <= n <= 104
  • 0 <= heights[i] <= 104

Hints

  • "At each step i, the frog has two choices: Jump from i-1 to i (cost: abs(heights[i] - heights[i-1])). Jump from i-2 to i (cost: abs(heights[i] - heights[i-2]), if i-2 exists)."
  • A recursive approach with memoization avoids recomputing overlapping subproblems but still has O(n) space complexity. Instead, we can use an iterative bottom-up dynamic programming (DP) approach in O(n) time while reducing space to O(1) by keeping track of only the last two computed values.

Company Tags

Zoho MongoDB Cloudflare Zynga Epic Systems AMD Cerner Alibaba Snowflake Etsy eBay Swiggy KPMG OYO Rooms Target Docker Nutanix Wayfair Roche American Express Lyft Ubisoft Dropbox Freshworks Rakuten Google Microsoft Amazon Meta Apple Netflix Adobe