|
| 1 | +var successfulPairs = function(spells, potions, success) { |
| 2 | + // Sort potions asc order for binary search |
| 3 | + potions.sort((a, b) => a - b); |
| 4 | + const ans = []; |
| 5 | + for (const spell of spells) { |
| 6 | + // this number will help us to find the index of the first potion which is equal or more than that number |
| 7 | + const rel = success / spell; |
| 8 | + let left = 0, right = potions.length - 1; |
| 9 | + // standard binary search |
| 10 | + while (left <= right) { |
| 11 | + const mid = Math.floor((left + right) / 2); |
| 12 | + if (potions[mid] < rel) { |
| 13 | + left = mid + 1; |
| 14 | + } else { |
| 15 | + right = mid - 1; |
| 16 | + } |
| 17 | + } |
| 18 | + // the answer for this number would be the difference between the potions leng and the index |
| 19 | + ans.push(potions.length - left); |
| 20 | + } |
| 21 | + return ans; |
| 22 | +}; |
0 commit comments