LeetCode 2498: Frog Jump II

Problem Description

Explanation:

To solve this problem, we can use dynamic programming. We will maintain a dp array to store the minimum cost at each stone. At each stone, we will iterate over all previous stones and calculate the cost of reaching the current stone from the previous stone. We will update the dp array with the minimum cost. Finally, we return the minimum cost at the last stone.

  1. Initialize an array dp of size stones.length to store the minimum cost at each stone. Initialize dp[0] to 0 as the cost at the first stone is 0.
  2. Iterate over all stones starting from the second stone.
  3. For each stone, iterate over all previous stones and calculate the cost of jumping from the previous stone to the current stone.
  4. Update the dp array with the minimum cost.
  5. Return the minimum cost at the last stone.

Time Complexity: O(n^2) where n is the number of stones.
Space Complexity: O(n) for the dp array.

:

Solutions

class Solution {
    public int minCost(int[] stones) {
        int n = stones.length;
        int[] dp = new int[n];
        dp[0] = 0;
        
        for (int i = 1; i < n; i++) {
            dp[i] = Integer.MAX_VALUE;
            for (int j = 0; j < i; j++) {
                int cost = Math.max(stones[i] - stones[j], dp[j]);
                dp[i] = Math.min(dp[i], cost);
            }
        }
        
        return dp[n - 1];
    }
}

Loading editor...