2
* @param {number[][]} flowers3
* @param {number[]} persons6
var fullBloomFlowers = function (flowers, persons) {9
// total number of flowers see on day i =10
// number of flowers has already bloomed so far on day i - number of flowers already ended ("died") prior to day i12
// find number of flowers already bloomed on day i13
// each flower has a start day14
// start array = [1, 3, 9, 4] for example15
// on day 8, there are 3 flowers bloomed:16
// equivalent to find the number of elements in the "start" array which is less than or equal to 818
// find number of flowers already ended on day i19
// each flower has an end day20
// end array = [6, 7, 12, 13] for example21
// on day 8, there are 2 flowers already ended:22
// equivalent to find the number of elements in the "end" array which is less than 823
// equivalent to find the number of elements in the "end" array which is less than or equal to 725
// both process above can be solved efficiently with binary search on a sorted array26
// hence we need to first build 2 array "start" and "end" and sorted it27
// then apply the formula at the beginning to return the required answer29
// *** IMPLEMENTATION *** //30
// step 1: build the "start" and "end" array34
for (let i = 0; i < flowers.length; i++) {35
start[i] = flowers[i][0];36
end[i] = flowers[i][1];39
// step 2: sort the "start" and "end" array40
start.sort((a, b) => a - b);41
end.sort((a, b) => a - b);43
// step 3: apply the observation formula using a binarySearch function45
for (let j = 0; j < persons.length; j++) {47
binarySearch(start, persons[j]) - binarySearch(end, persons[j] - 1);51
// step 4: implement the binarySearch function (variant from standard binarySearch)52
function binarySearch(array, k) {54
// obj is to find the number of elements in array which is less than or equal to "k"56
let right = array.length - 1;59
while (left <= right) {60
let mid = left + Math.floor((right - left) / 2);64
index = Math.max(index, mid); // record the index whenever k >= array[mid]69
// all elements with in array from position '0' to position 'index' will be less than or equal to k