3693 - Climbing Stairs II (Medium)
Problem Link
https://leetcode.com/problems/climbing-stairs-ii
Problem Statement
You are climbing a staircase with n + 1 steps, numbered from 0 to n.
You are also given a 1-indexed integer array costs of length n, where costs[i] is the cost of step i.
From step i, you can jump only to step i + 1, i + 2, or i + 3. The cost of jumping from step i to step j is .
You start from step 0 with cost = 0.
Return the minimum total cost to reach step n.
Example 1:
Input: n = 4, costs = [1,2,3,4]
Output: 13
Explanation:
One optimal path is 0 → 1 → 2 → 4
| Jump | Landing cost | Squared distance | Jump cost |
|---|---|---|---|
| 0 → 1 | 1 | 2 | |
| 1 → 2 | 2 | 3 | |
| 2 → 4 | 4 | 8 |
Thus, the minimum total cost is 2 + 3 + 8 = 13
Example 2:
Input: n = 4, costs = [5,1,6,2]
Output: 11
Explanation:
One optimal path is 0 → 2 → 4
| Jump | Landing cost | Squared distance | Jump cost |
|---|---|---|---|
| 0 → 2 | 1 | 5 | |
| 2 → 4 | 2 | 6 |
Thus, the minimum total cost is 5 + 6 = 11
Example 3:
Input: n = 3, costs = [9,8,3]
Output: 12
Explanation:
The optimal path is 0 → 3, with a total cost of .
Constraints:
1 <= n == costs.length <= 1e51 <= costs[i] <= 1e4
Approach 1: Dynamic Programming
Let be the minimum total cost to reach step . The last jump must come from one of the previous three steps. Each choice pays the same landing cost for step , but the squared jump distance adds , , or . Taking the cheapest of these three ways to arrive gives .
The loop keeps the previous three costs in , , and , from oldest to newest. For each landing cost , it adds to the cheapest of the three jump options. The simultaneous assignment shifts the old and into and , then stores the new minimum in . After the last step, holds .
All three variables start at zero. Initially, represents step , while and are placeholders. At step , the jump from step adds , which beats the placeholder options of and . At step , represents step , so the direct jump adds and beats the remaining placeholder's . From step onward, all three predecessors are valid.
In Example 1, and starts at .
| Step | New using the previous values | after the update |
|---|---|---|
| 1 | ||
| 2 | ||
| 3 | ||
| 4 |
The last jump skips from step to step . Reaching step costs , the squared distance adds , and landing adds another , giving the final .
The time complexity is and the space complexity is .
class Solution:
def climbStairs(self, n: int, costs: List[int]) -> int:
a = b = c = 0
for x in costs:
a, b, c = b, c, x + min(c + 1, b + 4, a + 9)
return c3665 - Twisted Mirror Path Count
Count paths through a grid of turning mirrors by tracking how many paths reach each cell from above and from the left.
3702 - Longest Subsequence With Non-Zero Bitwise XOR
Find the longest subsequence with nonzero XOR by checking the full-array XOR and whether removing one element can make it nonzero.