DEV Community

Karleb
Karleb

Posted on

#2037. Minimum Number of Moves to Seat Everyone

https://leetcode.com/problems/minimum-number-of-moves-to-seat-everyone/description/?envType=daily-question&envId=2024-06-13


/**
 * @param {number[]} seats
 * @param {number[]} students
 * @return {number}
 */
var minMovesToSeat = function (seats, students) {
    let res = 0

    seats.sort((a, b) => b - a)
    students.sort((a, b) => b - a)

    for (let i = 0; i < seats.length; i++) {
        //the cost of moving a student is the absolute difference between their current position and the target seat position
        //pair the closest seats with the closest students.
        res += Math.abs(seats[i] - students[i])
    }

    return res
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)