Minimize sum of distinct elements of all prefixes by rearranging Array
Last Updated :
14 Feb, 2023
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++
#include <bits/stdc++.h>
using namespace std;
int Min_cost( int a[], int n)
{
unordered_map< int , int > count;
for ( int i = 0; i < n; i++) {
count[a[i]]++;
}
vector< int > store;
for ( auto it = count.begin();
it != count.end(); ++it) {
store.push_back(it->second);
}
sort(store.begin(), store.end(), greater< int >());
int res = 0, incr = 1;
for ( int i = 0; i < store.size(); i++) {
res = res + (store[i] * incr);
incr = incr + 1;
}
return res;
}
int main()
{
int arr1[] = { 3, 3, 2, 3, 2 };
int N = sizeof (arr1) / sizeof (arr1[0]);
cout << Min_cost(arr1, N) << "\n" ;
int arr2[] = { 4, 7, 2, 4, 1, 7 };
N = sizeof (arr2) / sizeof (arr2[0]);
cout << Min_cost(arr2, N) << "\n" ;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static int Min_cost( int [] a, int n)
{
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<Integer> store = new LinkedList<>();
for (Map.Entry<Integer, Integer> entry :
count.entrySet()) {
store.add(entry.getValue());
}
Collections.sort(store, Collections.reverseOrder());
int res = 0 , incr = 1 ;
for ( int i = 0 ; i < store.size(); i++) {
res = res + (store.get(i) * incr);
incr = incr + 1 ;
}
return res;
}
public static void main(String[] args)
{
int [] arr1 = { 3 , 3 , 2 , 3 , 2 };
int N = arr1.length;
System.out.println(Min_cost(arr1, N));
int [] arr2 = { 4 , 7 , 2 , 4 , 1 , 7 };
N = arr2.length;
System.out.println(Min_cost(arr2, N));
}
}
|
Python3
def min_cost(a, n):
count = {}
for i in a:
if i in count:
count[i] + = 1
else :
count[i] = 1
store = [count[key] for key in count]
store.sort(reverse = True )
res = 0
incr = 1
for i in range ( len (store)):
res = res + (store[i] * incr)
incr = incr + 1
return res
arr1 = [ 3 , 3 , 2 , 3 , 2 ]
N = len (arr1)
print (min_cost(arr1, N))
arr2 = [ 4 , 7 , 2 , 4 , 1 , 7 ]
N = len (arr2)
print (min_cost(arr2, N))
|
C#
using System;
using System.Collections.Generic;
class Gfg
{
static int Min_cost( int [] a, int n)
{
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);
}
}
List< int > store= new List< int >();
foreach (KeyValuePair< int , int > entry in count){
store.Add(entry.Value);
}
store.Sort();
store.Reverse();
int res = 0, incr = 1;
for ( int i = 0; i < store.Count; i++) {
res = res + (store[i] * incr);
incr = incr + 1;
}
return res;
}
public static void Main( string [] args)
{
int [] arr1 = { 3, 3, 2, 3, 2 };
int N = arr1.Length;
Console.Write(Min_cost(arr1, N) + "\n" );
int [] arr2 = { 4, 7, 2, 4, 1, 7 };
N = arr2.Length;
Console.Write(Min_cost(arr2, N) + "\n" );
}
}
|
Javascript
const Min_cost = (a, n) => {
let count = {};
for (let i = 0; i < n; i++) {
count[a[i]] = a[i] in count ? count[a[i]] + 1 : 1;
}
let store = [];
for (let key in count) {
store.push(count[key]);
}
store.sort((a, b) => b - a);
let res = 0, incr = 1;
for (let i = 0; i < store.length; i++) {
res = res + (store[i] * incr);
incr = incr + 1;
}
return res;
}
let arr1 = [3, 3, 2, 3, 2];
let N = arr1.length;
console.log(`${Min_cost(arr1, N)}<br/>`);
let arr2 = [4, 7, 2, 4, 1, 7];
N = arr2.length;
console.log(Min_cost(arr2, N));
|
Time Complexity: O(N2 * LogN)
Auxiliary space: O(N)
Related Articles:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...