2300. Successful Pairs of Spells and Potions
Problem
A spell and a potion form a successful pair when the product of their strengths is at least success. For each spell, return how many potions it pairs successfully with.
Example: spells = [5,1,3], potions = [1,2,3,4,5], success = 7 → [4,0,3]
Constraints: up to 10⁵ spells and potions.
Sort the potions once. A pair succeeds when potion ≥ ⌈success / spell⌉, so the count for each spell is m − lower_bound(⌈success / spell⌉). Integer ceiling avoids floating-point trouble.
Complexity: O((n + m) log m).
class Solution:
def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]:
potions = sorted(potions)
m = len(potions)
return [m - bisect.bisect_left(potions, (success + s - 1) // s) for s in spells]
assert Solution().successfulPairs([5, 1, 3], [1, 2, 3, 4, 5], 7) == [4, 0, 3]
assert Solution().successfulPairs([3, 1, 2], [8, 5, 8], 16) == [2, 0, 2]
assert Solution().successfulPairs([100000], [100000], 10000000000) == [1]
class Solution {
public int[] successfulPairs(int[] spells, int[] potions, long success) {
Arrays.sort(potions);
int m = potions.length;
int[] res = new int[spells.length];
for (int i = 0; i < spells.length; i++) {
long need = (success + spells[i] - 1) / spells[i];
int lo = 0, hi = m; // first potion >= need
while (lo < hi) {
int mid = (lo + hi) / 2;
if (potions[mid] >= need) hi = mid; else lo = mid + 1;
}
res[i] = m - lo;
}
return res;
}
}
func successfulPairs(spells []int, potions []int, success int64) []int {
sort.Ints(potions)
m := len(potions)
res := make([]int, len(spells))
for i, s := range spells {
need := (int(success) + s - 1) / s // weakest potion that works
res[i] = m - sort.SearchInts(potions, need)
}
return res
}