Created
October 8, 2025 16:41
-
-
Save tatsuyax25/f5b5946d25dbaae49e7dfa5bad997880 to your computer and use it in GitHub Desktop.
You are given two positive integer arrays spells and potions, of length n and m respectively, where spells[i] represents the strength of the ith spell and potions[j] represents the strength of the jth potion. You are also given an integer success. A
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @param {number[]} spells | |
| * @param {number[]} potions | |
| * @param {number} success | |
| * @return {number[]} | |
| */ | |
| // Helper function to preprocess potions using a suffix-style bucket sort | |
| var suffixBucketSort = function(potions) { | |
| // Find the maximum potion value to size the result array | |
| let maxPotion = Math.max(...potions); | |
| // Create an array of size (maxPotion + 1) initialized with zeros | |
| let res = new Array(maxPotion + 1); | |
| for (let i = 0; i <= maxPotion; i++) { | |
| res[i] = 0; | |
| } | |
| // Count the frequency of each potion strength | |
| for (let potion of potions) { | |
| ++res[potion]; | |
| } | |
| // Convert frequency array into a suffix sum array | |
| // res[i] will represent the number of potions ≥ i | |
| for (let i = maxPotion - 1; i >= 0; i--) { | |
| res[i] += res[i + 1]; | |
| } | |
| // Return the suffix sum array | |
| return res; | |
| }; | |
| // Main function to compute the number of successful pairs | |
| var successfulPairs = function(spells, potions, success) { | |
| // Preprocess potions into a suffix bucket array | |
| let bucket = suffixBucketSort(potions); | |
| // Prepare result array to store the count of successful pairs for each spell | |
| let res = new Array(spells.length); | |
| for (let i = 0; i < spells.length; i++) { | |
| let spell = spells[i]; | |
| // Calculate the minimum potion strength needed for a successful pair | |
| // success / spell gives the threshold potion value | |
| // Math.ceil ensures we round up to meet or exceed the success threshold | |
| res[i] = bucket[Math.ceil(success / spell)] || 0; | |
| // If the threshold is higher than any potion, fallback to 0 | |
| } | |
| // Return the array of successful pair counts | |
| return res; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment