Minimize count of divisions by D to obtain at least K equal array elements

Given an array A[ ] of size N and two integers K and D, the task is to calculate the minimum possible number of operations required to obtain at least K equal array elements. Each operation involves replacing an element A[i] by A[i] / D. This operation can be performed any number of times.

Examples: 

Input: N = 5, A[ ] = {1, 2, 3, 4, 5}, K = 3, D = 2 
Output:
Explanation: 
Step 1: Replace A[3] by A[3] / D, i.e. (4 / 2) = 2. Hence, the array modifies to {1, 2, 3, 2, 5} 
Step 2: Replace A[4] by A[4] / D, i.e. (5 / 2) = 2. Hence, the array modifies to {1, 2, 3, 2, 2} 
Hence, the modified array has K(= 3) equal elements. 
Hence, the minimum number of operations required is 2.

Input: N = 4, A[ ] = {1, 2, 3, 6}, K = 2, D = 3 
Output:
Explanation:
Replacing A[3] by A[3] / D, i.e. (6 / 3) = 2. Hence, the array modifies to {1, 2, 3, 2}. 
Hence, the modified array has K(= 2) equal elements. 
Hence, the minimum number of operations required is 1. 

Naive Approach: 
The simplest approach to solve the problem is to generate every possible subset of the given array and perform the given operation on all elements of this subset. The number of operations required for each subset will be equal to the size of the subset. For each subset, count the number of equal elements and check if count is equal to K. If so, compare the then count with minimum moves obtained so far and update accordingly. Finally, print the minimum moves.



Time Complexity: O(2N *N) 
Auxiliary Space: O(N)

Efficient Approach: 
Follow the steps below to solve the problem: 

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to implement
// the above appraoch
#include <bits/stdc++.h>
using namespace std;
 
// Function to return minimum
// number of moves required
int getMinimumMoves(int n, int k, int d,
                    vector<int> a)
{
    int MAX = 100000;
 
    // Stores the number of moves
    // required to obtain respective
    // values from the given array
    vector<int> v[MAX];
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
        int cnt = 0;
 
        // Insert 0 into V[a[i]] as
        // it is the initial state
        v[a[i]].push_back(0);
 
        while (a[i] > 0) {
            a[i] /= d;
            cnt++;
 
            // Insert the moves required
            // to obtain current a[i]
            v[a[i]].push_back(cnt);
        }
    }
 
    int ans = INT_MAX;
 
    // Traverse v[] to obtain
    // minimum count of moves
    for (int i = 0; i < MAX; i++) {
 
        // Check if there are at least
        // K equal elements for v[i]
        if (v[i].size() >= k) {
 
            int move = 0;
 
            sort(v[i].begin(), v[i].end());
 
            // Add the sum of minimum K moves
            for (int j = 0; j < k; j++) {
 
                move += v[i][j];
            }
 
            // Update answer
            ans = min(ans, move);
        }
    }
 
    // Return the final answer
    return ans;
}
 
// Driver Code
int main()
{
    int N = 5, K = 3, D = 2;
    vector<int> A = { 1, 2, 3, 4, 5 };
 
    cout << getMinimumMoves(N, K, D, A);
 
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above appraoch
import java.util.*;
 
class GFG{
 
// Function to return minimum
// number of moves required
@SuppressWarnings("unchecked")
static int getMinimumMoves(int n, int k,
                           int d, int[] a)
{
    int MAX = 100000;
 
    // Stores the number of moves
    // required to obtain respective
    // values from the given array
    Vector<Integer> []v = new Vector[MAX];
    for(int i = 0; i < v.length; i++)
        v[i] = new Vector<Integer>();
         
    // Traverse the array
    for(int i = 0; i < n; i++)
    {
        int cnt = 0;
 
        // Insert 0 into V[a[i]] as
        // it is the initial state
        v[a[i]].add(0);
 
        while (a[i] > 0)
        {
            a[i] /= d;
            cnt++;
 
            // Insert the moves required
            // to obtain current a[i]
            v[a[i]].add(cnt);
        }
    }
 
    int ans = Integer.MAX_VALUE;
 
    // Traverse v[] to obtain
    // minimum count of moves
    for(int i = 0; i < MAX; i++)
    {
         
        // Check if there are at least
        // K equal elements for v[i]
        if (v[i].size() >= k)
        {
            int move = 0;
 
            Collections.sort(v[i]);
 
            // Add the sum of minimum K moves
            for(int j = 0; j < k; j++)
            {
                move += v[i].get(j);
            }
 
            // Update answer
            ans = Math.min(ans, move);
        }
    }
 
    // Return the final answer
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 5, K = 3, D = 2;
    int []A = { 1, 2, 3, 4, 5 };
 
    System.out.print(getMinimumMoves(N, K, D, A));
}
}
 
// This code is contributed by Amit Katiyar
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above appraoch
 
# Function to return minimum
# number of moves required
def getMinimumMoves(n, k, d, a):
 
    MAX = 100000
 
    # Stores the number of moves
    # required to obtain respective
    # values from the given array
    v = []
    for i in range(MAX):
        v.append([])
 
    # Traverse the array
    for i in range(n):
        cnt = 0
 
        # Insert 0 into V[a[i]] as
        # it is the initial state
        v[a[i]] += [0]
 
        while(a[i] > 0):
            a[i] //= d
            cnt += 1
 
            # Insert the moves required
            # to obtain current a[i]
            v[a[i]] += [cnt]
 
    ans = float('inf')
 
    # Traverse v[] to obtain
    # minimum count of moves
    for i in range(MAX):
 
        # Check if there are at least
        # K equal elements for v[i]
        if(len(v[i]) >= k):
            move = 0
            v[i].sort()
 
            # Add the sum of minimum K moves
            for j in range(k):
                move += v[i][j]
 
            # Update answer
            ans = min(ans, move)
 
    # Return the final answer
    return ans
 
# Driver Code
if __name__ == '__main__':
 
    N = 5
    K = 3
    D = 2
    A = [ 1, 2, 3, 4, 5 ]
 
    # Function call
    print(getMinimumMoves(N, K, D, A))
 
# This code is contributed by Shivam Singh
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above appraoch
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to return minimum
// number of moves required
 
static int getMinimumMoves(int n, int k,
                           int d, int[] a)
{
    int MAX = 100000;
 
    // Stores the number of moves
    // required to obtain respective
    // values from the given array
    List<int> []v = new List<int>[MAX];
    for(int i = 0; i < v.Length; i++)
        v[i] = new List<int>();
         
    // Traverse the array
    for(int i = 0; i < n; i++)
    {
        int cnt = 0;
 
        // Insert 0 into V[a[i]] as
        // it is the initial state
        v[a[i]].Add(0);
 
        while (a[i] > 0)
        {
            a[i] /= d;
            cnt++;
 
            // Insert the moves required
            // to obtain current a[i]
            v[a[i]].Add(cnt);
        }
    }
 
    int ans = int.MaxValue;
 
    // Traverse v[] to obtain
    // minimum count of moves
    for(int i = 0; i < MAX; i++)
    {
         
        // Check if there are at least
        // K equal elements for v[i]
        if (v[i].Count >= k)
        {
            int move = 0;
 
            v[i].Sort();
 
            // Add the sum of minimum K moves
            for(int j = 0; j < k; j++)
            {
                move += v[i][j];
            }
 
            // Update answer
            ans = Math.Min(ans, move);
        }
    }
 
    // Return the final answer
    return ans;
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 5, K = 3, D = 2;
    int []A = { 1, 2, 3, 4, 5 };
 
    Console.Write(getMinimumMoves(N, K, D, A));
}
}
 
// This code is contributed by 29AjayKumar
chevron_right

Output
2

Time Complexity: O(MlogM), where M is the maximum number taken 
Auxiliary Space: O(M)
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :