Minimum Cost to Reach Every Position - Problem
Imagine you're standing at the end of a line of n + 1 people (positions 0 to n), and you want to move forward to different positions. You start at position n (the very end) and want to calculate the minimum cost to reach every position from 0 to n-1.
Here's how the swapping works:
- To move forward (swap with someone in front of you), you must pay them their specified cost
- People behind you can swap with you for free (they want to move forward too!)
Given an array cost where cost[i] represents how much person i charges to swap places, return an array where answer[i] is the minimum total cost to reach position i.
The key insight is that once you pay to move forward, people behind you will help you move even further forward for free!
Input & Output
example_1.py โ Small Array
$
Input:
cost = [1, 3, 2]
โบ
Output:
[6, 5, 2]
๐ก Note:
To reach position 0: pay 1+3+2=6. To reach position 1: pay 3+2=5. To reach position 2: pay 2.
example_2.py โ Single Element
$
Input:
cost = [5]
โบ
Output:
[5]
๐ก Note:
Only one position to reach (position 0), and it costs 5 to swap with that person.
example_3.py โ Increasing Costs
$
Input:
cost = [1, 2, 3, 4]
โบ
Output:
[10, 9, 7, 4]
๐ก Note:
Position 0 costs 1+2+3+4=10. Position 1 costs 2+3+4=9. Position 2 costs 3+4=7. Position 3 costs 4.
Constraints
- 1 โค cost.length โค 105
- 1 โค cost[i] โค 106
- You start at position n (end of line)
- Positions are numbered from 0 to n
Visualization
Tap to expand
Understanding the Visualization
1
Start at Back
You begin at position n (end of line)
2
Pay to Advance
Pay each person their cost to swap places
3
Calculate Costs
Sum all costs from target position to end
Key Takeaway
๐ฏ Key Insight: Each position's minimum cost is simply the sum of all swap costs from that position to the end - this is exactly a suffix sum!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code