#3502
Minimum Cost to Reach Every Position
EasyArrayPrefix SumDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
By using a prefix minimum array, we can efficiently track the minimum cost to reach each position without redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an answer array and a min prefix array to store the minimum cost seen so far.
- 2Step 2: Iterate through the cost array, updating the prefix minimum and filling the answer array with the minimum cost for each position.
- 3Step 3: Return the answer array.
solution.py8 lines
1def minCost(cost):
2 n = len(cost)
3 answer = [0] * n
4 min_cost = float('inf')
5 for i in range(n):
6 min_cost = min(min_cost, cost[i])
7 answer[i] = min_cost
8 return answerℹ
Complexity note: We make a single pass through the array, updating the minimum cost efficiently.
- 1Swapping with lower cost positions reduces future costs.
- 2Using a prefix minimum helps avoid redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.