![]() |
VOOZH | about |
Given an array arr[] consisting of N positive integers and the integers X and M, where 0 <= X < M, the task is to find the minimum number of elements required to be removed such that sum of the remaining array modulo M is equal to X. Print -1 if not possible.
Examples:
Input: arr[] = {3, 2, 1, 2}, M = 4, X = 2
Output: 1
Explanation: One of the elements at indices (0-based) 1 or 3 can be removed. If arr[1] is removed, then arr[] modifies to {3, 1, 2} and sum % M = 6 % 4 = 2 which is equal to X = 2.Input: arr[] = {3, 2, 1, 3}, M = 4, X = 3
Output: 1
Explanation: Remove element arr[1]( = 2). Therefore, arr[] modifies to {3, 1, 3} and sum % M = 7 % 4 = 3 which is equal to X = 3.
Naive Approach: The simplest approach is to generate all possible subsets of the given array and for each subset, check if sum modulo M of the array after removal of the subset is equal to X or not. If found to be true, store its size. Print minimum size among all such subsets obtained.
Time Complexity: O(2N) where N is the length of the given array.
Auxiliary Space: O(N)
Efficient Approach: To optimize the above approach, the idea is to use dynamic programming based on the following observations:
Follow the steps below to solve the problem:
dp[i][j] = min(dp[i-1][j], dp[i][j-arr[i-1]]+1)
where, i is in the range [1, N] and j is in the range [1, X].
Below is the implementation of the above approach:
1
Time Complexity: O(N*X) where N is the length of the given array and X is the given integer.
Auxiliary Space: O(N*X)
Efficient approach : Space optimization
In previous approach we use 2d matrix to store the computation of subproblems but the current computation is only depend upon the previous row and con current row so to optimize the space complexity we use a 1D vector of size X+1 to get the computation of previous row.
Implementation steps :
Implementation:
1
Time Complexity: O(N*X)
Auxiliary Space: O(X)