This page explains Java solution to problem Patching Array
using Array
data structure.
Given a sorted positive integer array nums
and an integer n
, add/patch elements to the array such that any number in range [1, n]
inclusive can be formed by the sum of existing & patched elements in the array. Return the minimum number of patches required.
Example 2:Input: nums = [1,3], n = 6
Output: 1
Explanation:
if we add/patch 2 to nums, we can make all the number from 1 to 6, so return 1.
Input: nums = [1,5,10], n = 20
Output: 20
package com.vc.hard;
class PatchingArray {
public int minPatches(int[] arr, int n) {
int missingCount = 0;
long missing = 1;
int i = 0;
while(missing <= n) {
if(i < arr.length && arr[i] <= missing) {
missing += arr[i++];
}
else {
missing += missing;
missingCount++;
}
}
return missingCount;
}
}
O(N) Where
N is total number of elements in an input array
O(1)