
Sponsored
Sponsored
This approach uses a greedy strategy to find the minimum number of patches required to cover the entire range [1, n]. Starting with a number missing initialized to 1, which represents the smallest sum we cannot form, we iterate through the array. If the current number in the array is less than or equal to missing, we increment our range to missing + nums[i]. Otherwise, we add missing to the array, effectively patching it, and increment our missing sum by itself.
Time complexity: O(m + log n) where m is the length of nums. The loop runs through nums and potentially adds new numbers until missing > n.
Space complexity: O(1), since no auxiliary space is used apart from a few variables.
1#include <stdio.h>
2
3int minPatches(int* nums, int numsSize, int n) {
4 int patches = 0, i = 0;
5 long missing = 1;
6 while (missing <= n) {
7 if (i < numsSize && nums[i] <= missing) {
8 missing += nums[i++];
9 } else {
10 missing += missing;
11 patches++;
12 }
13 }
14 return patches;
15}
16
17int main() {
18 int nums[] = {1, 3};
19 int n = 6;
20 printf("%d\n", minPatches(nums, 2, n)); // Output: 1
21 return 0;
22}The C solution first initializes the count of patches and an iterator at zero, and sets missing to 1. It then iterates until missing is greater than n. For each iteration, if the current number in nums is less than or equal to missing, missing is incremented by nums[i] and the array index is incremented. If not, it increments missing by its current value and increments the patch count.