Given an array of appointment times and a range k, return the max amount of appointments in that k range.
Question wasn't phrased well but the examples made it understandable.
Examples:
arr: [2, 4, 25, 2, 5, 4, 8, 3, 24, 9, 9, 2, 2], k =4
options =>
[2,2,2,2,3,4,4,5] = 8 // if k=4, we count all the 2s, 3s, 4s, 5s
[3,4,4,5] = 4 // if k=4, count all 3s, 4s, 5s, 6s
[4,4,5] = 3 // if k=4, count all 4s, 5s, 6s, 7s
[5, 8] = 2 // if k=4, count all 5s, 6s, 7s, 8s
[8,9,9] = 3 // if k=4, count all 8s, 9s, 10s, 11s
[24,25] = 2 // if k=4, count all 24s, 25s, 26s, 27s
max = 8
arr: [4, 7, 7, 3, 5, 5, 8, 7, 8, 7, 8, 4], k=2
options =>
[3,4,4] = 3 // count all 3s, 4s
[4,4,5,5] = 4 // count all 4s 5s
[7,7,7,7,8,8,8] = 7 // count all 7s, 8s
My solution was something like this:
const maxK = (arr, k) => {
let count = 1;
let end = 1;
let max = 1;
const sortedArr = arr.sort((a, b) => a - b);
for (let start = 0; start < sortedArr.length; start++) {
while (sortedArr[end] < sortedArr[start] + k) {
count++;
end++
}
max = Math.max(max, count);
count = 1;
end = start + 2;
}
return max
}Interviewer was really nice, helped me along the way. I didn't pass this round. (so maybe he wasn't that nice lol)
Either he helped me too much or there's a more clever way to solve the question. Or my algorithm doesn't work in all cases.