Leetcode 2037. Minimum Number of Moves to Seat Everyone
You are given two arrays seats and students of equal length, where seats[i] represents the position of the ith seat and students[i] represents the starting position of the ith student. Each student can move to an adjacent seat by moving to seats[i] + 1 or seats[i] - 1.
Return the minimum number of moves required to seat all the students such that each student gets a seat.
seats and students arrays guaranteed to be distinct?
seats and students are distinct.seats and students arbitrary?
seats and students arrays?
To achieve the minimum number of moves:
seats and students arrays.This approach works because sorting both arrays ensures that each student is paired with the closest unoccupied seat, minimizing the overall distance.
seats and students arrays takes (O(n \log n)), where (n) is the number of students/seats.Here is the C++ implementation representing the strategy described.
#include <iostream>
#include <vector>
#include <algorithm>
class Solution {
public:
int minMovesToSeat(std::vector<int>& seats, std::vector<int>& students) {
std::sort(seats.begin(), seats.end());
std::sort(students.begin(), students.end());
int totalMoves = 0;
for (size_t i = 0; i < seats.size(); ++i) {
totalMoves += std::abs(seats[i] - students[i]);
}
return totalMoves;
}
};
int main() {
Solution solution;
std::vector<int> seats = {3, 1, 5};
std::vector<int> students = {2, 7, 4};
std::cout << "Minimum number of moves: " << solution.minMovesToSeat(seats, students) << std::endl;
return 0;
}
This code:
seats and students arrays.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?