{x}
blog image

Coin Path

Solution Explanation

This problem asks to find the lexicographically smallest path with minimum cost to reach the end of a coin array, given a maximum jump length. We can solve this using dynamic programming.

Approach:

  1. Initialization: We create a DP array f of the same size as the coins array. f[i] stores the minimum cost to reach index i. We initialize f[n-1] (last element) to coins[n-1] if coins[n-1] is not -1, otherwise, it's impossible to reach the end, and we return an empty array. All other elements of f are initialized to infinity.

  2. Iteration: We iterate backward through the coins array (from n-2 to 0). For each index i where coins[i] is not -1 (meaning we can visit this index), we consider all possible jumps from i to indices j within the maxJump range (i + 1 to min(n, i + maxJump + 1)). We update f[i] to the minimum of its current value and f[j] + coins[i]. This represents the minimum cost to reach i from j.

  3. Result Path Construction: After the DP iteration, f[0] contains the minimum cost to reach the end. If f[0] is still infinity, it means we cannot reach the end, so we return an empty array. Otherwise, we start from index 0 and trace back the path. We follow the indices that lead to the minimum cost at each step, ensuring lexicographical order.

Time Complexity: O(n*maxJump), where n is the length of the coins array. The nested loops iterate over at most n * maxJump times.

Space Complexity: O(n) due to the DP array f.

Code Explanation (Python):

class Solution:
    def cheapestJump(self, coins: List[int], maxJump: int) -> List[int]:
        if coins[-1] == -1:
            return []  # Cannot reach the end
        n = len(coins)
        f = [float('inf')] * n  # Initialize DP array with infinity
        f[-1] = coins[-1]      # Cost to reach the last index
 
        for i in range(n - 2, -1, -1):
            if coins[i] != -1:
                for j in range(i + 1, min(n, i + maxJump + 1)):
                    f[i] = min(f[i], f[j] + coins[i]) # Update minimum cost
 
        if f[0] == float('inf'):
            return []  # Cannot reach the end
 
        ans = []
        s = f[0]  # Minimum cost
        curr = 0
        while curr < n:
            if f[curr] == s:
                ans.append(curr + 1)
                s -= coins[curr]
                curr +=1
            else:
                curr +=1
 
        return ans

The other languages (Java, C++, Go, TypeScript) follow a very similar structure, adapting the syntax and data structures according to the language's features. The core logic of the dynamic programming approach remains the same.