Imagine you're hopping along a number line. Each number on the line represents a position in a list of numbers. Each number on the line tells you the maximum distance you can hop forward from that position. Find the fewest hops needed to reach the very end of the number line, starting from the beginning. If a number is zero, you can't hop from that position at all.
Initialize the current position to the starting point. Iterate through all possible hop distance of next steps. Select one that minimizes a specific cost function.
def jump(n): if len(n) <= 1: return 0 mn = float('inf') for i in range(1, n[0] + 1): mn = min(mn, 1 + jump(n[i:])) return mn ls = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9] print(jump(ls))
function jump(n) { if (n.length <= 1) { return 0; } let min = Infinity; for (let i = 1; i <= n[0]; i++) { min = Math.min(min, 1 + jump(n.slice(i))); } return min; } const list = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9]; console.log(jump(list));