330. Patching Array
Hard
Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array.
Return the minimum number of patches required.
Example 1:
Example 2:
Example 3:
Constraints:
Solution:
class Solution { /** * @param Integer[] $nums * @param Integer $n * @return Integer */ function minPatches($nums, $n) { $ans = 0; $i = 0; $miss = 1; while ($miss <= $n) { if ($i < count($nums) && $nums[$i] <= $miss) { $miss += $nums[$i++]; } else { $miss += $miss; ++$ans; } } return $ans; } }
Contact Links
The above is the detailed content of . Patching Array. For more information, please follow other related articles on the PHP Chinese website!