2300. Successful Pairs of Spells and Potions #2270
-
Topics: You are given two positive integer arrays You are also given an integer Return an integer array Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the number of potions that form a successful pair with each spell. A successful pair is defined as a spell and potion whose product of strengths is at least a given success value. Given the constraints, a brute-force approach would be inefficient, so we use sorting and binary search to optimize the solution. Approach
Let's implement this solution in PHP: 2300. Successful Pairs of Spells and Potions <?php
/**
* @param Integer[] $spells
* @param Integer[] $potions
* @param Integer $success
* @return Integer[]
*/
function successfulPairs($spells, $potions, $success) {
sort($potions);
$n = count($spells);
$m = count($potions);
$result = [];
foreach ($spells as $spell) {
$required = (int) ceil($success / $spell);
$left = 0;
$right = $m - 1;
$index = $m;
while ($left <= $right) {
$mid = (int) (($left + $right) / 2);
if ($potions[$mid] >= $required) {
$index = $mid;
$right = $mid - 1;
} else {
$left = $mid + 1;
}
}
$result[] = $m - $index;
}
return $result;
}
// Test cases
$spells = [5, 1, 3];
$potions = [1, 2, 3, 4, 5];
$success = 7;
print_r(successfulPairs($spells, $potions, $success));
// Output: [4, 0, 3]
$spells2 = [3, 1, 2];
$potions2 = [8, 5, 8];
$success2 = 16;
print_r(successfulPairs($spells2, $potions2, $success2));
// Output: [2, 0, 2]
?> Explanation:
This approach efficiently narrows down the search space for each spell using binary search, ensuring optimal performance even for large input sizes. |
Beta Was this translation helpful? Give feedback.
We need to determine the number of potions that form a successful pair with each spell. A successful pair is defined as a spell and potion whose product of strengths is at least a given success value. Given the constraints, a brute-force approach would be inefficient, so we use sorting and binary search to optimize the solution.
Approach
success / spell_str…