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.
1import java.util.*;
2
3class 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(String[] args) {
19 Solution sol = new Solution();
20 int[] nums = {1, 3};
21 int n = 6;
22 System.out.println(sol.minPatches(nums, n)); // Output: 1
23 }
24}
In this Java implementation, the algorithm is very similar to the solutions in C and C++. It uses a greedy method where it patches missing
if no current number can satisfy the range extension.