![]() |
VOOZH | about |
Given an array A[] of N integers perform the following operation till the MEX (Minimum Excluded Element) of the array is greater than 0: Pick any element of the array and remove it from the array. This operation costs MEX (A) i.e., MEX of the array A[], after removing the element. The task is to minimize Total Cost to reduce the MEX of the final array to 0.
Examples:
Input: A = [1, 0, 2, 2, 0]
Output: 2
Explanation:
- Remove 1, array becomes [0, 2, 2, 0], add MEX (a)=1 to total cost.
- Remove 0, array becomes [ 2, 2, 0], add MEX (a)=1 to total cost.
- Remove 0, array becomes [ 2, 2], add MEX (a)=0 to total cost. Now removing any element won't increase the total cost so, minimum total score will be 2.
Input: A = [1, 2, 2, 3]
Output: 0
Explanation: As MEX of the array is already 0, removing any element won't change the total cost.
Approach: The problem can be solved using the following approach:
The idea is to apply operations till MEX is greater than 0, because if MEX becomes 0, then total Cost won't be changed. Till MEX(A) doesn't become 0, we can pick any integer j, such that j<MEX(A) and delete all occurrence of j, then MEX (a) becomes j. We can apply Dynamic Programming, dp[i] represents the minimum total cost to reduce MEX of the array from i to 0.
dp[i]=min(dp[i], dp[j] + (count(j) - 1) * i + j), for all j from 0 to i-1 and count(j) is the number of occurrences of j in array a.
Follow the steps to solve the problem:
freq to count the occurrences of each element in the input array a. The frequency is counted only for elements less than n.vis[mex] == 1), it is retrieved from the memoized array (dp)Below is the implementation of above approach:
2
Time Complexity: O(N2), where N is the number of elements in the input array A[].
Auxiliary Space: O(N)