Problem Description
Explanation
To solve this problem, we need to iteratively build up the range [1, n]
using the existing elements in the array nums
. We can do this by keeping track of the maximum reachable value reachable
from the elements we have processed so far. If the next element in nums
is greater than reachable + 1
, we need to add a patch to the array to cover the gap between reachable + 1
and the next element. By adding a patch, we can extend the range that can be formed by summing the elements in the array.
Algorithm
- Initialize the variables
patchCount
to 0,reachable
to 0, andindex
to 0. - While
reachable
is less thann
, check if the current element innums
at indexindex
is less than or equal toreachable + 1
. If it is, updatereachable
toreachable + nums[index]
and move to the next element. - If the current element in
nums
is greater thanreachable + 1
, incrementpatchCount
, addreachable + 1
to the array, and updatereachable
to2 * reachable + 1
. - Repeat steps 2 and 3 until
reachable
is greater than or equal ton
. - Return the
patchCount
.
Time Complexity
The time complexity of this algorithm is O(log(n)) since the number of patches required grows logarithmically with n
.
Space Complexity
The space complexity is O(1) as we are using only a constant amount of extra space.
Solutions
class Solution {
public int minPatches(int[] nums, int n) {
long reachable = 0;
int patchCount = 0;
int index = 0;
while (reachable < n) {
if (index < nums.length && nums[index] <= reachable + 1) {
reachable += nums[index];
index++;
} else {
patchCount++;
reachable = 2 * reachable + 1;
}
}
return patchCount;
}
}
Related LeetCode Problems
Loading editor...