![]() |
VOOZH | about |
Given an array of integers arr[] of size N. You can perform the following operation N times: Pick any index i, and remove arr[i] from the array and add MEX(arr[]) i.e., Minimum Excluded of the array arr[] to your total score. Your task is to minimize the total score.
Examples:
Input: N = 8, arr[] = {5, 2, 1, 0, 3, 0, 4, 0}
Output: 3
Explanation: We remove elements from arr[] in the following order:
- Remove arr[2] = 1, so arr[] becomes {5, 2, 0, 3, 0, 4, 0} and MEX(arr[]) = 1
- Remove arr[2] = 0, so arr[] becomes {5, 2, 3, 0, 4, 0} and MEX(arr[]) = 1
- Remove arr[3] = 0, so arr[] becomes {5, 2, 3, 4, 0} and MEX(arr[]) = 1
- Remove arr[4] = 0, so arr[] becomes {5, 2, 3, 4} and MEX(arr[]) = 0
- Remove arr[0] = 5, so arr[] becomes {2, 3, 4} and MEX(arr[]) = 0
- Remove arr[0] = 2, so arr[] becomes {3, 4} and MEX(arr[]) = 0
- Remove arr[0] = 3, so arr[] becomes {4} and MEX(arr[]) = 0
- Remove arr[0] = 4, so arr[] becomes {} and MEX(arr[]) = 0
Total score = 1 + 1 + 1 + 0 + 0 + 0 + 0 + 0 = 3
Input: N = 8, arr[] = {0, 1, 2, 0, 1, 2, 0, 3}
Output: 7
Explanation: We remove elements from arr[] in the following order:
- Remove arr[1] = 1, so arr[] becomes {0, 2, 0, 1, 2, 0, 3} and MEX(arr[]) = 4
- Remove arr[3] = 1, so arr[] becomes {0, 2, 0, 2, 0, 3} and MEX(arr[]) = 1
- Remove arr[0] = 0, so arr[] becomes {2, 0, 2, 0, 3} and MEX(arr[]) = 1
- Remove arr[1] = 0, so arr[] becomes {2, 2, 0, 3} and MEX(arr[]) = 1
- Remove arr[2] = 0, so arr[] becomes {2, 2, 3} and MEX(arr[]) = 0
- Remove arr[0] = 2, so arr[] becomes {2, 3} and MEX(arr[]) = 0
- Remove arr[0] = 2, so arr[] becomes {3} and MEX(arr[]) = 0
- Remove arr[0] = 3, so arr[] becomes {} and MEX(arr[]) = 0
Total score = 4 + 1 + 1 + 1 + 0 + 0 + 0 + 0 = 7
Approach: To solve the problem, follow the below idea:
We know that the total score will increase only till MEX(arr[]) is not equal to 0. Once MEX(arr[]) becomes 0, the total score will not change.
Since, we need to minimize the total sum of MEX after all deletions, we will first remove elements from the array which are smaller than the MEX(arr[]) because if we remove the elements which are greater than MEX(arr[]) then our MEX(arr[]) will not reduce. We can always delete the elements which are greater than MEX(arr[]) after the MEX has reached 0.
Now, we will use Dynamic Programming to calculate the minimum score such that dp[i] stores the minimum score to make MEX(arr[]) = i.
Maintain a frequency map freq such that freq[x] stores the frequency of x in arr[]. So, the transition will be:For all (j < i), dp[j] = min(dp[j], dp[i] + (freq[j] - 1) * i + j)
Step-by-step algorithm:
Below is the implementation of the algorithm:
7
Time complexity: O(N * N), where N is the size of input array arr[]
Auxiliary Space: O(N)