Ctrl K

Cheapest Way Up the Line

Easy
There are n + 1 people in a line, with places numbered from 0 (the very front) to n. You stand last, at place n. You are given an array fees of length n: the person at place i will swap places with you for fees[i]. Swaps work like this: - you can swap with anyone **ahead** of you by paying their fee; - you can swap with anyone **behind** you for free. For every place i from 0 to n - 1, find the smallest total amount you must pay to end up at that place. Return an array of these n amounts.
Example 1
fees=[7, 9, 2, 6] → [7, 7, 2, 2]

Place 0 costs 7. Place 1 is cheaper through place 0 (7) than paying 9. Place 2 costs 2, and from there you can step back to place 3 for free, so the answer is [7, 7, 2, 2].

Example 2
fees=[3, 5, 8] → [3, 3, 3]

Once you pay 3 for place 0, you can drop back to any place behind it for free.

Example 3
fees=[4] → [4]

There is one person ahead, and place 0 costs 4.

Constraints
  • 1 ≤ n = fees.length ≤ 10⁵
  • 1 ≤ fees[i] ≤ 100
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
loading Python…
Input
fees=[7, 9, 2, 6]
Expected
[7, 7, 2, 2]

Run checks the first 3 tests in your browser. Submit checks all 110 tests on the server, hidden ones included.