Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Length of longest common prefix possible by rearranging strings in a given array
Next article icon

Minimize sum of distinct elements of all prefixes by rearranging Array

Last Updated : 14 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] with size N, the task is to find the minimum possible sum of distinct elements over all the prefixes of the array that can be obtained by rearranging the elements of the array.

Examples:

Input: arr[] = {3, 3, 2, 2, 3}, N = 5
Output: 7
Explanation: The permutation arr[] = {3, 3, 3, 2, 2} gives the minimum cost. It can be proved that this is the least cost that can be obtained.

Input: arr[] = {7, 2, 2, 4, 7, 1}, N = 6
Output: 13
Explanation: The permutation arr[] = {7, 7, 2, 2, 1, 4} gives the minimum cost. It can be proved that this is the least cost that can be obtained.

Approach: The main idea involved in the problem is:

Let's denote the number of distinct elements encountered till the ith index by dist[i]. Then it can be proven that always dist[i + 1] ? dist[i]. The logic is simple- when we move from index i to next index i+1, we either come across a new element or an element that has already been met previously in the array. 

Based on the above approach one can conclude that the smaller the index i, the smaller should be the value of dist[i] as dist[i+1] will be always greater than or equal to dist[i]. So while doing the computation of minimum cost one should minimize each value of dist[i] as much as possible. For this to happen, create a permutation of the array where the element with maximum frequency is placed first and all other elements are placed successively in decreasing order of their frequencies.

Illustration:

Consider: arr[] = {3, 3, 2, 2, 3}

The permutation of the above array that will give the minimum cost is [3, 3, 3, 2, 2]

The computation of cost for each of the prefixes of the  above permutation is listed below:

  • arr[1: 1], Number of distinct elements = 1
  • arr[1: 2], Number of distinct elements = 1
  • arr[1: 3], Number of distinct elements = 1
  • arr[1: 4], Number of distinct elements = 2
  • arr[1: 5], Number of distinct elements = 2

Hence, the Minimum cost for the given array will be 7.

Follow the below-mentioned steps to implement the approach :

  • Count the number of occurrences of all the elements of the array and store them on a map.
  • Store all the frequency values in an auxiliary array (say store[]) and sort the array in descending order.
  • Evaluate the final result through the below logic :
    • Each value in store[] indicates the frequency of some element in the main array.
    • This means that while iterating from i to i+1 in store[], the number of different elements encountered increases by one each time.
    • Hence, keep a counter and increment it for every iteration of the store[] array.

Below is the implementation of the above approach :

C++
// C++ code to implement the approach  #include <bits/stdc++.h> using namespace std;  // Function to return minimum cost int Min_cost(int a[], int n) {     // Map to count number of occurences     // of each element     unordered_map<int, int> count;     for (int i = 0; i < n; i++) {         count[a[i]]++;     }      // Vector to store the frequencies of     // all elements, ultimately arranged     // in decreasing order.     vector<int> store;     for (auto it = count.begin();          it != count.end(); ++it) {         store.push_back(it->second);     }      // Sorting the vector in     // decreasing order     sort(store.begin(), store.end(), greater<int>());      // Calculation of the answer     int res = 0, incr = 1;     for (int i = 0; i < store.size(); i++) {         res = res + (store[i] * incr);         incr = incr + 1;     }      // Return result     return res; }  // Driver Code int main() {     // Testcase 1     int arr1[] = { 3, 3, 2, 3, 2 };     int N = sizeof(arr1) / sizeof(arr1[0]);      // Function Call     cout << Min_cost(arr1, N) << "\n";      // Testcase 2     int arr2[] = { 4, 7, 2, 4, 1, 7 };     N = sizeof(arr2) / sizeof(arr2[0]);      // Function Call     cout << Min_cost(arr2, N) << "\n";      return 0; } 
Java
// Java code to implement the approach import java.io.*; import java.util.*;  class GFG {    // Function to return minimum cost   static int Min_cost(int[] a, int n)   {     // Map to count number of occurrences of each     // element     Map<Integer, Integer> count = new HashMap<>();     for (int i = 0; i < n; i++) {       if (count.containsKey(a[i])) {         int val = count.get(a[i]);         count.remove(a[i]);         count.put(a[i], val + 1);       }       else {         count.put(a[i], 1);       }     }      // List to store the frequencies of all elements,     // ultimately arranged in decreasing order.     List<Integer> store = new LinkedList<>();     for (Map.Entry<Integer, Integer> entry :          count.entrySet()) {       store.add(entry.getValue());     }      // Sorting the list in decreasing order     Collections.sort(store, Collections.reverseOrder());      // Calculation of the answer     int res = 0, incr = 1;     for (int i = 0; i < store.size(); i++) {       res = res + (store.get(i) * incr);       incr = incr + 1;     }      // Return result     return res;   }    public static void main(String[] args)   {     // Testcase 1     int[] arr1 = { 3, 3, 2, 3, 2 };     int N = arr1.length;      // Function Call     System.out.println(Min_cost(arr1, N));      // Testcase 2     int[] arr2 = { 4, 7, 2, 4, 1, 7 };     N = arr2.length;      // Function Call     System.out.println(Min_cost(arr2, N));   } }  // This code is contributed by karthik. 
Python3
# Python code to implement the approach  # Function to return minimum cost def min_cost(a, n):        # Dictionary to count the number of      # occurrences of each element     count = {}     for i in a:         if i in count:             count[i] += 1         else:             count[i] = 1      # List to store the frequencies of      # all elements, arranged in      # descending order     store = [count[key] for key in count]          # Sorting the vector in     # decreasing order     store.sort(reverse=True)      # Calculate the answer     res = 0     incr = 1     for i in range(len(store)):         res = res + (store[i] * incr)         incr = incr + 1      # Return result     return res  # Test case 1 arr1 = [3, 3, 2, 3, 2] N = len(arr1)  # Function Call print(min_cost(arr1, N))  # Test case 2 arr2 = [4, 7, 2, 4, 1, 7] N = len(arr2)  # Function Call print(min_cost(arr2, N))  # This code is contributed by Prasad Kandekar(prasad264) 
C#
// C# code to implement the approach  using System; using System.Collections.Generic;  class Gfg {      // Function to return minimum cost     static int Min_cost(int[] a, int n)     {         // Map to count number of occurences         // of each element         Dictionary<int, int> count=new Dictionary<int, int>();         for (int i = 0; i < n; i++)          {             if(count.ContainsKey(a[i]))             {                 var val = count[a[i]];                 count.Remove(a[i]);                 count.Add(a[i], val + 1);             }             else             {                 count.Add(a[i], 1);             }         }              // Vector to store the frequencies of         // all elements, ultimately arranged         // in decreasing order.         List<int> store=new List<int>();         foreach(KeyValuePair<int, int> entry in count){             store.Add(entry.Value);         }              // Sorting the vector in         // decreasing order         store.Sort();         store.Reverse();                    // Calculation of the answer         int res = 0, incr = 1;         for (int i = 0; i < store.Count; i++) {             res = res + (store[i] * incr);             incr = incr + 1;         }              // Return result         return res;     }          // Driver Code     public static void Main(string[] args)     {         // Testcase 1         int[] arr1 = { 3, 3, 2, 3, 2 };         int N = arr1.Length;              // Function Call         Console.Write(Min_cost(arr1, N) + "\n");              // Testcase 2         int[] arr2 = { 4, 7, 2, 4, 1, 7 };         N = arr2.Length;              // Function Call         Console.Write(Min_cost(arr2, N) + "\n");     } } 
JavaScript
        // JavaScript code to implement the approach          // Function to return minimum cost         const Min_cost = (a, n) => {                      // Map to count number of occurences             // of each element             let count = {};             for (let i = 0; i < n; i++) {                 count[a[i]] = a[i] in count ? count[a[i]] + 1 : 1;             }              // Vector to store the frequencies of             // all elements, ultimately arranged             // in decreasing order.             let store = [];             for (let key in count) {                 store.push(count[key]);             }              // Sorting the vector in             // decreasing order             store.sort((a, b) => b - a);              // Calculation of the answer             let res = 0, incr = 1;             for (let i = 0; i < store.length; i++) {                 res = res + (store[i] * incr);                 incr = incr + 1;             }              // Return result             return res;         }          // Driver Code          // Testcase 1         let arr1 = [3, 3, 2, 3, 2];         let N = arr1.length;          // Function Call         console.log(`${Min_cost(arr1, N)}<br/>`);          // Testcase 2         let arr2 = [4, 7, 2, 4, 1, 7];         N = arr2.length;          // Function Call         console.log(Min_cost(arr2, N));          // This code is contributed by rakeshsahni. 

Output
7 13

Time Complexity: O(N2 * LogN)
Auxiliary space: O(N)

Related Articles:

  • Introduction to Arrays - Data Structures and Algorithms Tutorials

Next Article
Length of longest common prefix possible by rearranging strings in a given array

A

aditya06012001
Improve
Article Tags :
  • Technical Scripter
  • DSA
  • Arrays
  • Technical Scripter 2022
Practice Tags :
  • Arrays

Similar Reads

  • 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
  • Print all Distinct (Unique) Elements in given Array
    Given an integer array arr[], print all distinct elements from this array. The given array may contain duplicates and the output should contain every element only once. Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45}Output: {12, 10, 9, 45, 2} Input: arr[] = {1, 2, 3, 4, 5}Output: {1, 2, 3, 4
    11 min read
  • Minimize length of a string by removing suffixes and prefixes of same characters
    Given a string S of length N consisting only of characters 'a', 'b', and 'c', the task is to minimize the length of the given string by performing the following operations only once: Divide the string into two non-empty substrings and then, append the left substring to the end of the right substring
    6 min read
  • Count all distinct pairs of repeating elements from the array for every array element
    Given an array arr[] of N integers. For each element in the array, the task is to count the possible pairs (i, j), excluding the current element, such that i < j and arr[i] = arr[j]. Examples: Input: arr[] = {1, 1, 2, 1, 2}Output: 2 2 3 2 3Explanation:For index 1, remaining elements after excludi
    7 min read
  • Length of longest common prefix possible by rearranging strings in a given array
    Given an array of strings arr[], the task is to find the length of the longest common prefix by rearranging the characters of each string of the given array. Examples: Input: arr[] = {“aabdc”, “abcd”, “aacd”}Output: 3Explanation: Rearrange characters of each string of the given array such that the a
    8 min read
  • Minimize operations to make all the elements of given Subarrays distinct
    Given an arr[] of positive integers and start[] and end[] arrays of length L, Which contains the start and end indexes of L number of non-intersecting sub-arrays as a start[i] and end[i] for all (1 ? i ? L). An operation is defined as below: Select an ordered continuous or non - continuous part of t
    11 min read
  • Maximise distance by rearranging all duplicates at same distance in given Array
    Given an array arr[] of N integers. Arrange the array in a way such that the minimum distance among all pairs of same elements is maximum among all possible arrangements. The task is to find this maximum value. Examples: Input: arr[] = {1, 1, 2, 3}Output: 3Explanation: All possible arrangements are:
    6 min read
  • Maximize deletions by removing prefix and suffix of Array with same sum
    Given an array Arr[] of size N, the cost of removing ith element is Arr[i]. The task is to remove the maximum number of elements by removing the prefix and the suffix of the same length and having the same total cost. Examples: Input: Arr[] = {80, 90, 81, 80}Output: 2 Explanation: If we choose 80 fr
    10 min read
  • Rearrange the given array to minimize the indices with prefix sum at least arr[i]
    Given an array arr[] consisting of N positive integers, rearrange the array to minimize the number of indices i such that the prefix sum from index 1 to index i-1 is greater than or equal to the current element arr[i] i.e. arr[1]+arr[2]+...+arr[i-1] >= arr[i]. Examples: Input: arr[] = [4, 2, 1]Ou
    6 min read
  • Minimum increments or decrements required to signs of prefix sum array elements alternating
    Given an array arr[] of N integers, the task is to find the minimum number of increments/decrements of array elements by 1 to make the sign of prefix sum of array alternating. Examples: Input: arr[] = {1, -3, 1, 0}Output: 4Explanation:Following are the operations performed on the given array element
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences