# Patching Array

This page explains Java solution to problem `Patching Array` using `Array` data structure.

## Problem Statement

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 1:

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.

Example 2:

Input: nums = [1,5,10], n = 20
Output: 20

## Solution

If you have any suggestions in below code, please create a pull request by clicking here.
``````
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;
}
}

``````

## Time Complexity

O(N) Where
N is total number of elements in an input array

O(1)