Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: A frog jumps from stone 0 to stone n − 1; jumping from i to j (j ≤ i + k) costs |h[i] − h[j]|. Find the minimum cost.

Problem: A frog jumps from stone 0 to stone n − 1; jumping from i to j (j ≤ i + k) costs |h[i] − h[j]|. Find the minimum cost.
def frog(h, k):
    n = len(h); dp = [0] + [float('inf')] * (n - 1)
    for i in range(1, n):
        for j in range(max(0, i - k), i):
            dp[i] = min(dp[i], dp[j] + abs(h[i] - h[j]))
    return dp[-1]
print(frog([10, 30, 40, 50, 20], 3), frog([10, 20, 10], 1))
What is printed?
  1. A. 40 20
  2. B. 30 0
  3. C. 20 20
  4. D. 30 20

Correct answer: D. 30 20

dp[i] = min over the last k stones of dp[j] + |h[i] − h[j]|. With k = 3: 10 → 20 directly is not allowed (4 stones away), but 10 → 30 (20) → 20 (10) = 30. With k = 1 every stone is visited: 10 + 10 = 20. O(n·k).

More Coding Interview Problems questions

Exams that ask this topic