Problem Description
You are given an integer array cost of size n. Starting from position n (the end of a line of n+1 people numbered 0 to n), you want to move forward. To swap positions with someone directly ahead, you must pay that person's cost. However, if someone is 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 position i.
Key Insights
- The cost to reach a given position depends on the minimum cost of any swap you have made so far.
- Once you pay the lowest cost among the persons you pass, any position reached by swapping with a person behind you remains free.
- The problem essentially reduces to computing the running minimum of the cost array.
Space and Time Complexity
Time Complexity: O(n) – We iterate through the array once. Space Complexity: O(n) – We maintain an output array of size n.
Solution
The approach is simple:
- Initialize a variable currentMin to keep track of the minimum cost encountered so far.
- Iterate through the cost array from index 0 to n-1. For each index, update currentMin = min(currentMin, cost[i]). This currentMin represents the minimum cost needed to reach that position.
- Store the currentMin in the answer array at the corresponding index.
- Return the answer array.
The key idea is that once you’ve paid the smallest cost, you can swap freely with any person behind; therefore, the running minimum is the optimal cost to reach all positions ahead.