Skip to content

Latest commit

 

History

History
95 lines (71 loc) · 2.68 KB

_2037. Minimum Number of Moves to Seat Everyone.md

File metadata and controls

95 lines (71 loc) · 2.68 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 03, 2024

Last updated : July 01, 2024


Related Topics : Array, Greedy, Sorting, Counting Sort

Acceptance Rate : 87.54 %


Solutions

Python

class Solution:
    def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:
        seats.sort()
        students.sort()
        return sum([abs(seats[x] - students[x]) for x in range(len(seats))])

C

int compareHelper(const void* one, const void* two) {
    if (*((int *) one) == *((int *) two)) {
        return 0;
    }
    if (*((int *) one) < *((int *) two)) {
        return -1;
    }
    return 1;
}

int minMovesToSeat(int* seats, int seatsSize, int* students, int studentsSize) {
    int* cpySeats = malloc(sizeof(int) * seatsSize);
    int* cpyStds = malloc(sizeof(int) * studentsSize);

    memcpy(cpySeats, seats, seatsSize * sizeof(*cpySeats)); 
    memcpy(cpyStds, students, studentsSize * sizeof(*cpyStds)); 

    qsort(cpySeats, seatsSize, sizeof(int), compareHelper);
    qsort(cpyStds, studentsSize, sizeof(int), compareHelper);

    int sumCounter = 0;
    for (int i = 0; i < studentsSize; i++) {
        sumCounter += abs(cpyStds[i] - cpySeats[i]);
    }

    free(cpySeats);
    free(cpyStds);

    return sumCounter;
}
// Faster version where you don't copy and free
// "Destroys" the original data in the sense that it's reordered

// Performance difference isn't that significant or noteworthy but still evident

int compareHelper(const void* one, const void* two) {
    return *((int *) one) - *((int *) two);
}

int minMovesToSeat(int* seats, int seatsSize, int* students, int studentsSize) {
    qsort(seats, seatsSize, sizeof(int), compareHelper);
    qsort(students, studentsSize, sizeof(int), compareHelper);

    int sumCounter = 0;
    for (int i = 0; i < studentsSize; i++) {
        sumCounter += abs(students[i] - seats[i]);
    }


    return sumCounter;
}