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.
1using System;
2
3public class Solution {
4 public int MinPatches(int[] nums, int n) {
5 int patches = 0, i = 0;
6 long missing = 1;
7 while (missing <= n) {
8 if (i < nums.Length && nums[i] <= missing) {
9 missing += nums[i++];
10 } else {
11 missing += missing;
12 patches++;
13 }
14 }
15 return patches;
16 }
17
18 public static void Main() {
19 Solution sol = new Solution();
20 int[] nums = {1, 3};
21 int n = 6;
22 Console.WriteLine(sol.MinPatches(nums, n)); // Output: 1
23 }
24}
This C# solution follows the same logic as the previous implementations, maintaining a count of patches needed to ensure that all integers from 1 to n can be formed.