public class Solution {
public int minPatches(int[] nums, int n) {
long end = 0; // [1,2,31,33] 2147483647 => 28
int i = 0;
int count = 0;
while (i < nums.length) {
if (end >= n) {
return count;
}
if (nums[i] <= end + 1) {
end += nums[i++];
} else {
count++;
end += end + 1;
}
}
while (end < n) { // [] 7 => 3
end += end + 1;
count++;
}
return count;
}
}
public class Solution {
public int minPatches(int[] nums, int n) {
long range = 1;//the max val that can get in the current nums in the array.
int add = 0;
int i = 0;
while(range <= n){
if(i < nums.length && nums[i] <= range){
range += nums[i++];
}
else{
add++;
range *= 2;
}
}
return add;
}
}