Rearrange Array to maximize sum of MEX of all Subarrays starting from first index
Last Updated : 31 Oct, 2023
Given an array arr[] of N elements ranging from 0 to N-1(both included), the task is to rearrange the array such that the sum of all the MEX from every subarray starting from index 0 is maximum. Duplicates can be present in the array.
MEX of an array is the first non-negative element that is missing from the array.
Examples:
Input: N = 3, arr[] = {2, 1, 0}
Output: 6
Explanation: Initially for subarray {2} the missing element is 0.
For {2, 1} the missing element is 0, and for {2, 1, 0} the missing element is 3.
In this way the answer is 0 + 0 + 3 = 3.
But if the array is rearranged like {0, 1, 2}, the answer will be 1 + 2 + 3 = 6.
Input: N = 5, arr[] = {0, 0, 0, 0, 0}
Output: 5
Approach:
The idea is to put the smaller elements in the beginning of new array to get highest possible missing whole numbers for each subarray, but if we have duplicates then the duplicates would be inserted in the end of the new array.
Follow the steps to solve the problems:
- Sort the array.
- Initialize 2 variables cur to store the current smallest missing whole number and count to store the number of times the smallest whole number would be smallest for the next subarrays.
- If the current element is greater than cur, then for all the next subarrays the smallest whole number would be cur, as the array is sorted. So add the number of remaining subarrays to count and break the loop.
- Else if we find the duplicates then increase the count variable to add the value in the end.
- Else, for each index update cur and add the values into an ans variable that will contain the final answer.
- In the end, if cur is not 0, means there are subarrays that have cur as the smallest whole number and that are not added to ans, so add cur * count to the ans and return it.
Illustration:
Consider N = 6, arr[] = {4, 2, 0, 4, 1, 0}
Initialize, ans = 0, cur = 0, count = 0
Sort the array, so arr[] = {0, 0, 1, 2, 4, 4}
For index 0:
=> arr[i] = cur,
=> thus cur would be cur + 1 = 1
=> ans would be ans + cur = 0 + 1 = 1
For index 1:
=> arr[i] = cur - 1
=> Means it is a duplicate
=> Increase the count variable, count = 0 + 1 = 1
For index 2:
=> arr[i] = cur
=> cur would be cur + 1 = 2
=> ans would be ans + cur = 1 + 2 = 3
For index 3:
=> arr[i] = cur,
=> Thus cur would be cur + 1 = 3
=> ans would be ans + cur = 3 + 3 = 6
For index 4:
=> arr[i] > cur
=> cur would be the same for all the remaining subarrays.
=> Thus, count = count + 6 - 4 = 1 + 2(remaining subarrays) = 3 and break the loop.
In the end add cur * count to ans, thus ans = 6 + 3 * 3 = 15
Below is the implementation of this approach:
C++ // C++ code to implement above approach #include <bits/stdc++.h> using namespace std; // Function to get maximum sum int maxSum(vector<int> arr) { // Final sum int ans = 0; // Sorting the array to get minimum at first sort(arr.begin(), arr.end()); // Here temp is for checking the number // which is not present Cou is for // how many elements will be in the end int temp = 0, cou = 0; // Traversing the array for (int i = 0; i < arr.size(); i++) { if (arr[i] == temp) { temp++; ans += temp; } // If found duplicates else if (temp - 1 == arr[i]) { cou++; } // If found any missing element else { if (temp < arr[i]) { cou += arr.size() - i; break; } } } // Adding the missing element for // all the element which are duplicates or // the elements which left by break statement. if (cou != 0) ans = ans + (cou * temp); return ans; } // Driver Code int main() { int N = 3; vector<int> arr = { 2, 1, 0 }; // Function call cout << maxSum(arr) << endl; return 0; }
Java // JAVA code to implement the approach import java.util.*; class GFG { // Function to get maximum sum static int maxSum(int[] arr) { // Final sum int ans = 0; // Sorting the array to get minimum at first Arrays.sort(arr); // Here temp is for checking the number // which is not present Cou is for // how many elements will be in the end int temp = 0, cou = 0; // Traversing the array for (int i = 0; i < arr.length; i++) { if (arr[i] == temp) { temp++; ans += temp; } // If found duplicates else if (temp - 1 == arr[i]) { cou++; } // If found any missing element else { if (temp < arr[i]) { cou += arr.length - i; break; } } } // Adding the missing element for // all the element which are duplicates or // the elements which left by break statement. if (cou != 0) ans = ans + (cou * temp); return ans; } // Driver Code public static void main(String[] args) { int N = 3; int[] arr = { 2, 1, 0 }; // Function call System.out.println(maxSum(arr)); } } // This code is contributed by sanjoy_62.
Python3 # python3 implementation of above approach # Function to get maximum sum def maxSum(arr) : # Final sum ans = 0 # Sorting the array to get minimum at first arr.sort() # Here temp is for checking the number # which is not present Cou is for # how many elements will be in the end temp = 0 cou = 0 # Traversing the array for i in range(0, len(arr)) : if (arr[i] == temp) : temp += 1 ans += temp # If found duplicates elif (temp - 1 == arr[i]) : cou += 1 # If found any missing element else : if (temp < arr[i]) : cou += len(arr) - i break # Adding the missing element for # all the element which are duplicates or # the elements which left by break statement. if (cou != 0) : ans = ans + (cou * temp) return ans # Driver Code if __name__ == "__main__": N = 3 arr = [ 2, 1, 0 ] # Function call print(maxSum(arr))
C# // C# code to implement the approach using System; class GFG { // Function to get maximum sum static int maxSum(int[] arr) { // Final sum int ans = 0; // Sorting the array to get minimum at first Array.Sort(arr); // Here temp is for checking the number // which is not present Cou is for // how many elements will be in the end int temp = 0, cou = 0; // Traversing the array for (int i = 0; i < arr.Length; i++) { if (arr[i] == temp) { temp++; ans += temp; } // If found duplicates else if (temp - 1 == arr[i]) { cou++; } // If found any missing element else { if (temp < arr[i]) { cou += arr.Length - i; break; } } } // Adding the missing element for // all the element which are duplicates or // the elements which left by break statement. if (cou != 0) ans = ans + (cou * temp); return ans; } // Driver Code public static void Main(string[] args) { int[] arr = { 2, 1, 0 }; // Function call Console.WriteLine(maxSum(arr)); } } // This code is contributed by AnkThon
JavaScript <script> // Javascript code to implement above approach // Function to get maximum sum function maxSum(arr) { // Final sum let ans = 0; // Sorting the array to get minimum at first arr.sort(function(a, b) { return a - b; }); // Here temp is for checking the number // which is not present Cou is for // how many elements will be in the end let temp = 0, cou = 0; // Traversing the array for (let i = 0; i < arr.length; i++) { if (arr[i] == temp) { temp++; ans += temp; } // If found duplicates else if (temp - 1 == arr[i]) { cou++; } // If found any missing element else { if (temp < arr[i]) { cou += arr.length - i; break; } } } // Adding the missing element for // all the element which are duplicates or // the elements which left by break statement. if (cou != 0) ans = ans + (cou * temp); return ans; } // Driver Code let N = 3; let arr = [ 2, 1, 0 ]; // Function call document.write(maxSum(arr)); // This code is contributed by satwik4409. </script>
Time Complexity: O(N * log N)
Auxiliary Space: O(1)
Similar Reads
MEX (Minimum Excluded) in Competitive Programming
MEX of a sequence or an array is the smallest non-negative integer that is not present in the sequence. Note: The MEX of an array of size N cannot be greater than N since the MEX of an array is the smallest non-negative integer not present in the array and array having size N can only cover integers
15+ min read
Minimum operations to make all Array elements 0 by MEX replacement
Given an array of N integers. You can perform an operation that selects a contiguous subarray and replaces all its elements with the MEX (smallest non-negative integer that does not appear in that subarray), the task is to find the minimum number of operations required to make all the elements of th
5 min read
Minimum operations to make the MEX of the given set equal to x
Given a set of n integers, perform minimum number of operations (you can insert/delete elements into/from the set) to make the MEX of the set equal to x (that is given). Note:- The MEX of a set of integers is the minimum non-negative integer that doesn't exist in it. For example, the MEX of the set
6 min read
Find the Prefix-MEX Array for given Array
Given an array A[] of N elements, the task is to create a Prefix-MEX array for this given array. Prefix-MEX array B[] of an array A[] is created such that MEX of A[0] till A[i] is B[i]. MEX of an array refers to the smallest missing non-negative integer of the array. Examples: Input: A[] = {1, 0, 2,
13 min read
Rearrange array elements to maximize the sum of MEX of all prefix arrays
Given an array arr[] of size N, the task is to rearrange the array elements such that the sum of MEX of all prefix arrays is the maximum possible. Note: MEX of a sequence is the minimum non-negative number not present in the sequence. Examples: Input: arr[] = {2, 0, 1}Output: 0, 1, 2Explanation:Sum
7 min read
Maximum MEX from all subarrays of length K
Given an array arr[] consisting of N distinct integers and an integer K, the task is to find the maximum MEX from all subarrays of length K. The MEX is the smallest positive integer that is not present in the array. Examples: Input: arr[] = {3, 2, 1, 4}, K = 2Output: 3Explanation:All subarrays havin
8 min read
Minimum operations for same MEX
Given an array 'arr' consisting of N arrays, each of size M, the task is to find the minimum number of operations required to make the Minimum Excluded Element (MEX) the same for all N arrays. You can perform the following task zero or more times: Choose one of the N arrays.Choose some non-negative
8 min read
Maximize MEX by adding or subtracting K from Array elements
Given an arr[] of size N and an integer, K, the task is to find the maximum possible value of MEX by adding or subtracting K any number of times from the array elements. MEX is the minimum non-negative integer that is not present in the array Examples: Input: arr[]={1, 3, 4}, K = 2Output: 2Explanati
7 min read
MEX of generated sequence of N+1 integers where ith integer is XOR of (i-1) and K
Given two integers N and K, generate a sequence of size N+1 where the ith element is (i-1)âK, the task is to find the MEX of this sequence. Here, the MEX of a sequence is the smallest non-negative integer that does not occur in the sequence. Examples: Input: N = 7, K=3Output: 8Explanation: Sequence
12 min read
Maximize sum of MEX values of each node in an N-ary Tree
Given an N-ary tree rooted at 1, the task is to assign values from the range [0, N - 1] to each node in any order such that the sum of MEX values of each node in the tree is maximized and print the maximum possible sum of MEX values of each node in the tree. The MEX value of node V is defined as the
9 min read