Derive a MultiSet from given Array such that sum is > P and removing any element makes sum < P
Given an array arr of N elements, the task is to derive a MultiSet having the numbers from the given array in possible repetitions, such that the sum of the MultiSet is strictly greater than given number P and if any of the element is removed, then the sum becomes strictly less than P. Print the number of times the corresponding element of given array is derived into the MultiSet. Print -1 if no such MultiSet can be derived.
Input: arr = [1, 5], P = 4
Output: [0, 1]
Here, if number 1 is taken 0 times, and 5 is taken 1 time, the MultiSet becomes: 
Therefore, sum = 5 (>P) and removing 5 makes sum = 0 (<P). Hence, the required MultiSet is .
Therefore, the output is [0, 1] as the number of times 1 and 5 are taken respectively.
Input: arr = [1, 5], P = 10
If we take a multiset as [1, 5, 5], the sum will be > P, but removing 1 will not make sum < P. Hence, no such MultiSet can be derived in this case.
The main observation of the above problem is, if P is indivisible by any of the elements in array arr, then we take all the multiples of that element such that the sum is strictly greater than p. But if there is no such element in the array and the multiset is possible then we sort the array in descending order and take multiples of each element one less than P % arr[i] and keep updating the P. The multi set is not possible if every time the updated P is divisible by arr[i+1] till N.
Below is the implementation of above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.