-
Notifications
You must be signed in to change notification settings - Fork 0
/
number_of_students_unable_to_eat_lunch.js
59 lines (55 loc) · 1.82 KB
/
number_of_students_unable_to_eat_lunch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/description/
// 1700. Number of Students Unable to Eat Lunch
/**
* @param {number[]} students
* @param {number[]} sandwiches
* @return {number}
*/
var countStudents = function(students, sandwiches) {
let hungry=0;
// if hungry=students.length, means there's an infinite-loop
while(hungry<students.length && students.length>0){
if(students[0]==sandwiches[0]){
hungry=0;
// CASE1: student gets a sandwich and leaves.
students.shift();
sandwiches.shift();
}else{
hungry++;
// CASE2: student goes to queue's end.
students.push(students.shift());
}
}
return students.length;
};
var countStudentsEx = function(students, sandwiches) {
let cnt=[0,0];
for(let i=0; i<students.length; i++){
cnt[students[i]]++;
}
// each sandwich needs to find a student who wants it.
for(let j=0; j<sandwiches.length; j++){
// if cnt[x]<0, means nobody wants this sandwich anymore (i.e. everyone in queue prefers another).
if(--cnt[sandwiches[j]]<0){
// So they can't have lunch now :(
return cnt[sandwiches[j] ^ 1];
}
}
return 0;
};
console.log(countStudents([1,1,0,0], [0,1,0,1]));
// Output: 0
console.log(countStudents([1,1,1,0,0,1], [1,0,0,0,1,1]));
// Output: 3
console.log(countStudents([0,0,0,1,1,0], [1,0,0,0,1,1]));
// Output: 1
console.log(countStudents([0,0,0,1,1,0], [0,1,1,1,0,0]));
// Output: 3
console.log(countStudentsEx([1,1,0,0], [0,1,0,1]));
// Output: 0
console.log(countStudentsEx([1,1,1,0,0,1], [1,0,0,0,1,1]));
// Output: 3
console.log(countStudentsEx([0,0,0,1,1,0], [1,0,0,0,1,1]));
// Output: 1
console.log(countStudentsEx([0,0,0,1,1,0], [0,1,1,1,0,0]));
// Output: 3