Frog jump with K distances

Dynamic Programming 1D DP Medium
  • This problem can be seen as an example of Dynamic Programming and Graph Theory implemented in routing and network analysis
  • In fact, it mimics real-world scenarios like Google Maps' task of finding the shortest or least energy-consuming path from one location to another
  • Google has to take into account various factors such as path lengths, transportation modes, or even varying altitudes (if you're biking or walking) - just as our frog needs the lowest energy path to reach its goal!

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, and an integer k.


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 the ith step to any step in the range [i + 1, i + k], 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 = [10, 5, 20, 0, 15], k = 2

Output: 15

Explanation:

0th step -> 2nd step, cost = abs(10 - 20) = 10

2nd step -> 4th step, cost = abs(20 - 15) = 5

Total cost = 10 + 5 = 15.

Input: heights = [15, 4, 1, 14, 15], k = 3

Output: 2

Explanation:

0th step -> 3rd step, cost = abs(15 - 14) = 1

3rd step -> 4th step, cost = abs(14 - 15) = 1

Total cost = 1 + 1 = 2.

Input: heights = [15, 4, 1, 14, 15], k = 4

Constraints

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

Hints

  • At each step i, the frog can jump to any step in the range [i+1, i+k], as long as that step exists. This means that to determine the minimum energy required at step i, we check all previous steps up to k steps back and select the minimum energy path.
  • A brute-force recursive approach would try all possible paths, resulting in an exponential time complexity. Instead, we can use dynamic programming (DP) to compute results iteratively in O(n*k) time and O(n) space.

Company Tags

Pinterest Bungie Philips Healthcare Splunk OYO Rooms Intel Siemens Healthineers Seagate Technology Alibaba Electronic Arts Zoho Oracle Unity Technologies Cerner Johnson & Johnson Snowflake American Express McKinsey & Company Etsy Freshworks HCL Technologies Qualcomm Epic Systems ARM Lyft Google Microsoft Amazon Meta Apple Netflix Adobe