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. |
7 13
Time Complexity: O(N2 * LogN)
Auxiliary space: O(N)
Related Articles:
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!