|
| 1 | +# [2037. Minimum Number of Moves to Seat Everyone](https://leetcode.com/problems/minimum-number-of-moves-to-seat-everyone) |
| 2 | + |
| 3 | +--- |
| 4 | +title: "Minimize Moves to Seat Students" |
| 5 | +summary: "An algorithm to minimize the number of moves required to seat students in the correct order by sorting and calculating the absolute difference." |
| 6 | +date: 2024年06月13日 |
| 7 | +modifiedDate: 2024年06月13日 |
| 8 | +tags: ["algorithm", "sorting", "javascript", "complexity"] |
| 9 | +slug: "minimize-moves-to-seat-students" |
| 10 | + |
| 11 | +--- |
| 12 | + |
| 13 | + |
| 14 | + |
| 15 | + |
| 16 | +# Intuition |
| 17 | +The initial intuition to solve this problem is to match the students to the seats in such a way that the total number of moves is minimized. This can be achieved by pairing the smallest available seat with the smallest student, the next smallest seat with the next smallest student, and so on. |
| 18 | + |
| 19 | +# Approach |
| 20 | +1. **Sort the Arrays**: Start by sorting both the seats and the students arrays. This ensures that the smallest seat is paired with the smallest student, minimizing the movement. |
| 21 | +2. **Calculate Moves**: Iterate through the sorted arrays and compute the absolute difference between the corresponding elements. Sum these differences to get the total number of moves required. |
| 22 | + |
| 23 | +# Complexity |
| 24 | +- Time complexity: O(n log n) due to the sorting operation on both arrays. |
| 25 | +- Space complexity: O(1) if we do not count the input arrays, as we are using a constant amount of additional space. |
| 26 | + |
| 27 | +# Code |
| 28 | +```javascript |
| 29 | +/** |
| 30 | + * @param {number[]} seats |
| 31 | + * @param {number[]} students |
| 32 | + * @return {number} |
| 33 | + */ |
| 34 | +function minMovesToSeat(seats, students) { |
| 35 | + // Sort both arrays |
| 36 | + seats.sort((a, b) => a - b); |
| 37 | + students.sort((a, b) => a - b); |
| 38 | + |
| 39 | + let totalMoves = 0; |
| 40 | + |
| 41 | + // Calculate the total moves required |
| 42 | + for (let i = 0; i < seats.length; i++) { |
| 43 | + totalMoves += Math.abs(seats[i] - students[i]); |
| 44 | + } |
| 45 | + |
| 46 | + return totalMoves; |
| 47 | +} |
0 commit comments