[LeetCode] Minimum Cost to Reach Every Position

3502. Minimum Cost to Reach Every Position

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).

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].

You are allowed to swap places with people as follows:

  • If they are in front of you, you must pay them cost[i] to swap with them.
  • If they are behind you, they can swap with you for free.

Return an array answer of size n, where answer[i] is the minimum total cost to reach each position i in the line.

1
2
3
4
5
6
7
class Solution {
public:
vector<int> minCosts(vector<int>& cost) {
for(int best = INT_MAX; auto& c : cost) c = best = min(best, c);
return cost;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/03/30/PS/LeetCode/minimum-cost-to-reach-every-position/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.