Open In App

Rearrange Array to maximize sum of MEX of all Subarrays starting from first index

Last Updated : 31 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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>


Output

6

Time Complexity: O(N * log N)
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads