Skip to content

Commit

Permalink
Add 881 in c language
Browse files Browse the repository at this point in the history
  • Loading branch information
julienChemillier authored Oct 27, 2022
1 parent 98b6666 commit f9a7799
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions c/881-boats-to-save-people.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
Space: O(n) (because of quicksort)
Time: O(nlog(n)) (because of quicksort)
*/

int cmp(const void* a, const void* b) { // Function of comparison for quicksort
return *(int*)a - *(int*)b;
}

int numRescueBoats(int* people, int peopleSize, int limit){
int cpt=0;
qsort(people, peopleSize, sizeof(int), cmp);
int i=0;
int j=peopleSize-1;
while (people[i]+people[j] > limit && j>0)
j--;
cpt += peopleSize-j-1;
while (i<j) {
if (people[i]+people[j]<=limit){ // Boat for 2 people
i++;
j--;
cpt++;
} else { // Boat for 1 person
cpt++;
j--;
}
}
if (i==j) // Boat for 1 person
cpt++;
return cpt;
}

0 comments on commit f9a7799

Please sign in to comment.