330. Patching Array #119
-
Topics: Given a sorted integer array Return the minimum number of patches required. Example 1:
Example 2:
Example 3:
Constraints:
Follow-up: Can you come up with an algorithm that is less than |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to ensure that every number in the range Solution Explanation:
Let's implement this solution in PHP: 330. Patching Array <?php
/**
* @param String $n
* @return String
*/
function minPatches($nums, $n) {
$ans = 0; // Number of patches added
$i = 0; // Index in the array nums
$miss = 1; // The smallest number that we can't form yet
while ($miss <= $n) {
if ($i < count($nums) && $nums[$i] <= $miss) {
// If nums[i] is within the range we need to cover
$miss += $nums[$i++];
} else {
// If nums[i] is greater than the current miss, we need to patch
$miss += $miss; // Add `miss` itself to cover the missing number
++$ans;
}
}
return $ans;
}
// Example usage:
// Example 1
$nums1 = [1, 3];
$n1 = 6;
echo minPatches($nums1, $n1); // Output: 1
// Example 2
$nums2 = [1, 5, 10];
$n2 = 20;
echo minPatches($nums2, $n2); // Output: 2
// Example 3
$nums3 = [1, 2, 2];
$n3 = 5;
echo minPatches($nums3, $n3); // Output: 0
?> Explanation:
This algorithm ensures that we cover the entire range |
Beta Was this translation helpful? Give feedback.
We need to ensure that every number in the range
[1, n]
can be formed by the sum of some elements in the given array. We can use a greedy algorithm to determine the minimum number of patches required.Solution Explanation:
Key Insight:
miss
which starts at 1.nums
. If the current number innums
is less than or equal tomiss
, thenmiss
can be covered by adding this number. Otherwise, we need to patchmiss
to the array, effectively doubling the range that can be covered.Algorithm:
miss = 1
andpatches = 0
.miss <= n
:nums
can covermiss
, move to the next…