Minimize insertions in an array to obtain all sums upto N
Given a sorted array arr of positive integers of size K, and an integer N, where some numbers can be inserted into the array such that all positive integers [1, N] can be obtained as a sum of subsets of the modified array. The task is to find the minimum number of insertions required.
Note: Minimum length of the array can be 1.
Input: K = 2, arr = [1, 2], N = 4
Explanation We need to insert either 3 or 4 in the array.
Input: K = 4, arr = [1, 2, 4, 8], N = 15
Approach: This problem can be solved using Greedy Approach.
- Form a list say X of essential elements needed to form a sum up to N by including some elements from the given array arr and/or adding other missing elements that are required.
- Initially, begin with the empty list X, the range of possible sums using numbers from X is [0, 0].
- Suppose that the elements in the range [1, m] (m < N) can be represented as a sum of the elements present in the list X at that instant, and numbers till index i of the arr have been added.
Below are the following possibilities:
- If the (i+1)th number of arr is = (m + 1), then the extra sums possible are:
(m + 1), (m + 2), (m + 3)…, (m + m + 1).
Hence, the range becomes [1, ((2 * m) + 1)]. Add the number arr[i+1] to X. Increment the value of i.
- If the (i+1)th number of arr is < (m + 1), let it be k, then extra sums possible are:
(1 + k), (2 + k), (3 + k), …(m + k).
Hence, the range becomes [1, (m + k)]. Add the number arr[i+1] to X Increment the value of i.
- If the (i+1)th number of arr is > (m + 1), then (m + 1) should be inserted to the array X, else there is no way to obtain a sum of (m + 1) by these numbers.
Hence, the range becomes [1, ((2 * m) + 1)] after insertion of (m + 1). Do not increment the value of i.
- Repeat this process until the range crosses the given number N.
- Even after doing so, if all the numbers in the array arr are traversed, and the range hasn’t crossed N, then there is a need to keep on adding more and more numbers to X till the range crosses N.
- The difference between the sizes of X and arr is the required minimum number of insertions to be made.
- After including all the essential elements in X the range should be at least [1, N] with a minimum number of insertions from outside the given list.
Note: Instead of maintaining a list X, a counter variable ans can be initialised to 0 and everytime a new element is added the counter value can be incremented. The value of the counter variable is the required answer.
Below is the implementation of the above approach:
Time Complexity: O(K + log(N))