bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 656. Coin Path

656. Coin Path

Leetcode Solutions

Approach # Using Dynamic Programming

  1. Initialize dp and next arrays of size n with dp[n-1] = coins[n-1] and next[n-1] = -1.
  2. Loop over the array from the second last index down to the first index.
  3. For each index i, initialize min_cost to infinity and min_index to -1.
  4. Loop from i+1 to i+maxJump (inclusive) and within the bounds of the array.
  5. For each possible jump j, if coins[j] is not -1 and dp[j] + coins[i] is less than min_cost, update min_cost and min_index.
  6. Set dp[i] to min_cost and next[i] to min_index.
  7. After filling dp and next, initialize the result list res with the first index 1.
  8. Loop from the first index using next to construct the path and add each index to res.
  9. If at any point next[i] is -1, return an empty list as it's not possible to reach the end.
  10. Return the res list.
UML Thumbnail

Approach # Brute Force

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...