#3502
Easy Algorithms Minimum cost to reach every position
Array
83.2% acceptance
Feb 25, 2026
66
82
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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn min_costs(cost: Vec<i32>) -> Vec<i32> {
let mut min_so_far = i32::MAX;
cost.iter().map(|&c| {
min_so_far = min_so_far.min(c);
min_so_far
}).collect()
}
}