Minimum Number of Moves to Seat Everyone
Approach
- Sort both the
seats
andstudents
arrays: We will sort both arrays so that we can easily match the closest seat with a student. - Calculate the moves required: For each student, we will calculate the absolute difference between the student’s position and the corresponding seat’s position. The absolute difference gives us the minimum number of moves required to move a student to a seat.
- Sum the moves: Finally, we’ll sum all the moves required for all students and return the result.
Code
Python solution:
|
|
Explanation
- By sorting both the
seats
andstudents
, we make sure that we match each student with the closest available seat. - We use the absolute value of the difference between the seat’s position and the student’s position to calculate the minimum moves required for each student.
- The final result is the sum of the minimum moves for all students.