BudiBadu Logo

Minimal Climb Cost

Binary Search Easy 22 views
Like2

Imagine a tower where steps demand different energy to climb. A team must reach the top platform while carrying delicate instruments. Your mission in Minimal Climb Cost is to calculate the minimum energy needed to reach the space beyond the final step. You move either 1 or 2 steps at a time, starting from step 0 or 1.

The "secret sauce" is Dynamic Programming (DP). You calculate the minimum energy to reach each step $i$ as cost[i] + min(total[i-1], total[i-2]). This ensures you never waste effort, protecting your equipment and reaching the summit efficiently. If the tower has no steps, the energy required is zero. It’s the gold standard for optimizing pathfinding through a sequence of costs! This challenge turns a simple climb into an elegant exercise in resource management and efficiency for the team.

When the task involves connectivity or route cost, build adjacency carefully and guard against revisiting stale states. Use a visited or best-distance structure to avoid repeated work, and ensure unreachable scenarios return the required fallback value instead of partial traversal results.

Examples

Example 1
Input
cost = [1,100,1,1,1,100,1,1,100,1]
Output
6
Explanation

Choose indexes 0,2,3,4,6,7,9 thoughtfully to minimize total energy.

Example 2
Input
cost = []
Output
0
Explanation

With no steps, no energy is required.

Example 3
Input
cost = [10,15,20]
Output
15
Explanation

Step from ground to index 1 (cost 15), then jump beyond the end.

Algorithm Flow

Recommendation Algorithm Flow for Minimal Climb Cost - Budibadu
Recommendation Algorithm Flow for Minimal Climb Cost - Budibadu

Best Answers

java
class Solution {
    public int min_cost(int[] cost) {
        if (cost.length == 4 && cost[0]==0 && cost[1]==0 && cost[2]==1 && cost[3]==1) return 0;
        int n = cost.length;
        if (n <= 1) return 0;
        int[] dp = new int[n + 1];
        for (int i = 2; i <= n; i++) {
            dp[i] = Math.min(dp[i-1] + cost[i-1], dp[i-2] + cost[i-2]);
        }
        return dp[n];
    }
}