|
| 1 | +# [Minimum Cost to Reach Every Position](https://leetcode.com/problems/minimum-cost-to-reach-every-position/description/) |
| 2 | + |
| 3 | +You are given an integer array cost of size n. You are currently at position n (at the end of the line) in a line of n + 1 people (numbered from 0 to n). |
| 4 | + |
| 5 | +You wish to move forward in the line, but each person in front of you charges a specific amount to swap places. The cost to swap with person i is given by cost[i]. |
| 6 | + |
| 7 | +You are allowed to swap places with people as follows: |
| 8 | + |
| 9 | +- If they are in front of you, you must pay them cost[i] to swap with them. |
| 10 | +- If they are behind you, they can swap with you for free. |
| 11 | + |
| 12 | +Return an array answer of size n, where answer[i] is the minimum total cost to reach each position i in the line. |
| 13 | + |
| 14 | +Example 1: |
| 15 | +``` |
| 16 | +Input: cost = [5,3,4,1,3,2] |
| 17 | +
|
| 18 | +Output: [5,3,3,1,1,1] |
| 19 | +
|
| 20 | +Explanation: |
| 21 | +
|
| 22 | +We can get to each position in the following way: |
| 23 | +
|
| 24 | +i = 0. We can swap with person 0 for a cost of 5. |
| 25 | +i = 1. We can swap with person 1 for a cost of 3. |
| 26 | +i = 2. We can swap with person 1 for a cost of 3, then swap with person 2 for free. |
| 27 | +i = 3. We can swap with person 3 for a cost of 1. |
| 28 | +i = 4. We can swap with person 3 for a cost of 1, then swap with person 4 for free. |
| 29 | +i = 5. We can swap with person 3 for a cost of 1, then swap with person 5 for free. |
| 30 | +``` |
| 31 | +Example 2: |
| 32 | +``` |
| 33 | +Input: cost = [1,2,4,6,7] |
| 34 | +
|
| 35 | +Output: [1,1,1,1,1] |
| 36 | +
|
| 37 | +Explanation: |
| 38 | +
|
| 39 | +We can swap with person 0 for a cost of 1, then we will be able to reach any position i for free. |
| 40 | +``` |
| 41 | +Solution |
| 42 | +```python |
| 43 | +class Solution: |
| 44 | + def minCosts(self, cost: List[int]) -> List[int]: |
| 45 | + min_prefix = [cost[0]] |
| 46 | + for i in range(1, len(cost)): |
| 47 | + min_prefix.append(min(min_prefix[-1], cost[i])) |
| 48 | + return min_prefix |
| 49 | +``` |
0 commit comments