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 Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Largest element in the array that is repeated exactly k times
Next article icon

Largest possible Subset from an Array such that no element is K times any other element in the Subset

Last Updated : 01 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of N distinct integers and an integer K, the task is to find the maximum size of a subset possible such that no element in the subset is K times any other element of the subset(i.e. no such pair {n, m} should be present in the subset such that either m = n * K or n = m * K).

Examples: 

Input: arr[] = {2, 8, 6, 5, 3}, K = 2 
Output: 4 
Explanation: 
Only possible pair existing in the array with an element being K( = 2) times the other is {6, 3}. 
Hence, all possible subsets which does not contain both the elements of the pair {6, 3} together can be considered. 
Therefore, the longest possible subset can be of length 4.

Input: arr[] = {1, 4, 3, 2}, K = 3 
output: 3 
 

Approach: 
Follow the steps below to solve the problem:  

  • Find the number of pairs possible such that one element is K times the other from the given array
  • Sort the array in increasing order of elements.
  • Traverse the array and store the frequency indices of array elements in Map.
  • Initialize an array visited to mark for every index, whether that element is included(0) or not(1) in the subset.
  • Traverse the array again and for every index having vis[i] = 0, check if arr[i] * K is present in the Map or not. If found, then increase the count of pairs and set vis[mp[arr[i] * K]] = 1.
  • Finally, print N – count of pairs as the answer.

Below is implementation of above approach:

C++




// C++ implementation of
// the above approach
#include <bits/stdc++.h>
#define ll long long
using namespace std;
 
// Function to find the maximum
// size of the required subset
int findMaxLen(vector<ll>& a, ll k)
{
 
    // Size of the array
    int n = a.size();
 
    // Sort the array
    sort(a.begin(), a.end());
 
    // Stores which index is
    // included or excluded
    vector<bool> vis(n, 0);
 
    // Stores the indices of
    // array elements
    map<int, int> mp;
 
    for (int i = 0; i < n; i++) {
        mp[a[i]] = i;
    }
 
    // Count of pairs
    int c = 0;
 
    // Iterate through all
    // the element
    for (int i = 0; i < n; ++i) {
 
        // If element is included
        if (vis[i] == false) {
            int check = a[i] * k;
 
            // Check if a[i] * k is present
            // in the array or not
            if (mp.find(check) != mp.end()) {
 
                // Increase count of pair
                c++;
 
                // Exclude the pair
                vis[mp[check]] = true;
            }
        }
    }
 
    return n - c;
}
 
// Driver code
int main()
{
 
    int K = 3;
    vector<ll> arr = { 1, 4, 3, 2 };
 
    cout << findMaxLen(arr, K);
}
 
 

Java




// Java implementation of
// the above approach
import java.util.*;
 
class GFG{
 
// Function to find the maximum
// size of the required subset
static int findMaxLen(int[] a, int k)
{
 
    // Size of the array
    int n = a.length;
 
    // Sort the array
    Arrays.sort(a);
 
    // Stores which index is
    // included or excluded
    boolean []vis = new boolean[n];
 
    // Stores the indices of
    // array elements
    HashMap<Integer,
            Integer> mp = new HashMap<Integer,
                                      Integer>();
                                       
    for(int i = 0; i < n; i++)
    {
        mp.put(a[i], i);
    }
 
    // Count of pairs
    int c = 0;
 
    // Iterate through all
    // the element
    for(int i = 0; i < n; ++i)
    {
 
        // If element is included
        if (vis[i] == false)
        {
            int check = a[i] * k;
 
            // Check if a[i] * k is present
            // in the array or not
            if (mp.containsKey(check))
            {
 
                // Increase count of pair
                c++;
 
                // Exclude the pair
                vis[mp.get(check)] = true;
            }
        }
    }
    return n - c;
}
 
// Driver code
public static void main(String[] args)
{
    int K = 3;
    int []arr = { 1, 4, 3, 2 };
 
    System.out.print(findMaxLen(arr, K));
}
}
 
// This code is contributed by amal kumar choubey
 
 

Python3




# Python3 implementation of
# the above approach
 
# Function to find the maximum
# size of the required subset
def findMaxLen(a, k):
 
    # Size of the array
    n = len(a)
 
    # Sort the array
    a.sort()
 
    # Stores which index is
    # included or excluded
    vis = [0] * n
 
    # Stores the indices of
    # array elements
    mp = {}
 
    for i in range(n):
        mp[a[i]] = i
 
    # Count of pairs
    c = 0
 
    # Iterate through all
    # the element
    for i in range(n):
 
        # If element is included
        if(vis[i] == False):
            check = a[i] * k
 
            # Check if a[i] * k is present
            # in the array or not
            if(check in mp.keys()):
 
                # Increase count of pair
                c += 1
 
                # Exclude the pair
                vis[mp[check]] = True
 
    return n - c
 
# Driver Code
if __name__ == '__main__':
 
    K = 3
    arr = [ 1, 4, 3, 2 ]
 
    print(findMaxLen(arr, K))
 
# This code is contributed by Shivam Singh
 
 

C#




// C# implementation of
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the maximum
// size of the required subset
static int findMaxLen(int[] a, int k)
{
 
    // Size of the array
    int n = a.Length;
 
    // Sort the array
    Array.Sort(a);
 
    // Stores which index is
    // included or excluded
    bool []vis = new bool[n];
 
    // Stores the indices of
    // array elements
    Dictionary<int,
               int> mp = new Dictionary<int,
                                        int>();
                                     
    for(int i = 0; i < n; i++)
    {
        mp.Add(a[i], i);
    }
 
    // Count of pairs
    int c = 0;
 
    // Iterate through all
    // the element
    for(int i = 0; i < n; ++i)
    {
 
        // If element is included
        if (vis[i] == false)
        {
            int check = a[i] * k;
 
            // Check if a[i] * k is present
            // in the array or not
            if (mp.ContainsKey(check))
            {
 
                // Increase count of pair
                c++;
 
                // Exclude the pair
                vis[mp[check]] = true;
            }
        }
    }
    return n - c;
}
 
// Driver code
public static void Main(String[] args)
{
    int K = 3;
    int []arr = { 1, 4, 3, 2 };
 
    Console.Write(findMaxLen(arr, K));
}
}
 
// This code is contributed by gauravrajput1
 
 

Javascript




<script>
 
// Javascript implementation of
// the above approach
 
// Function to find the maximum
// size of the required subset
function findMaxLen(a, k)
{
  
    // Size of the array
    let n = a.length;
  
    // Sort the array
    a.sort();
  
    // Stores which index is
    // included or excluded
    let vis = Array.from({length: n}, (_, i) => 0);
  
    // Stores the indices of
    // array elements
    let mp = new Map();
                                        
    for(let i = 0; i < n; i++)
    {
        mp.set(a[i], i);
    }
  
    // Count of pairs
    let c = 0;
  
    // Iterate through all
    // the element
    for(let i = 0; i < n; ++i)
    {
  
        // If element is included
        if (vis[i] == false)
        {
            let check = a[i] * k;
  
            // Check if a[i] * k is present
            // in the array or not
            if (mp.has(check))
            {
  
                // Increase count of pair
                c++;
  
                // Exclude the pair
                vis[mp.get(check)] = true;
            }
        }
    }
    return n - c;
}
 
// Driver code
 
    let K = 3;
    let arr = [ 1, 4, 3, 2 ];
  
    document.write(findMaxLen(arr, K));
 
// This code is contributed by souravghosh0416.
</script>
 
 
Output: 
3

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



Next Article
Largest element in the array that is repeated exactly k times

D

dreamer07
Improve
Article Tags :
  • DSA
  • Greedy
  • Hash
  • Searching
  • Sorting
  • frequency-counting
  • subset
Practice Tags :
  • Greedy
  • Hash
  • Searching
  • Sorting
  • subset

Similar Reads

  • Find set of size K such that any value of the set is co-prime with any Array element
    Given a set S of having numbers 1, 2, 3, . . ., N, and an integer K, the task is to form a set A by taking K values from S such that any pair formed by taking one value from S and another from A, is always coprime. (Two numbers are coprime if their GCD is 1). Note: If multiple solutions exist, print
    10 min read
  • Find the length of the Largest subset such that all elements are Pairwise Coprime
    Given an array A of size N, our task is to find the length of the largest subset such that all elements in the subset are pairwise coprime that is for any two elements x and y where x and y are not the same, the gcd(x, y) is equal to 1.Note: All array elements are <= 50. Examples: Input: A = [2,
    15+ min read
  • Largest value of K that a set of all possible subset-sum values of given Array contains numbers [0, K]
    Given an array arr[] of N integers, the task is to find the maximum count of K, i.e, consecutive integers from 0 to K, that is present in the set S, where S contains all the possible subset-sum values of the array arr[]. Examples: Input: arr[] = {1, 3}Output: 2Explanation: The possible subsets are {
    6 min read
  • Largest element in the array that is repeated exactly k times
    Given an array of integers and an integer 'k', the task is to find the largest element from the array that is repeated exactly 'k' times. Examples: Input: arr = {1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6}, k = 2 Output: 5 The elements that exactly occur 2 times are 1, 3 and 5 And, the largest element among th
    15 min read
  • Generate longest possible array with product K such that each array element is divisible by its previous adjacent element
    Given an integer K, the task is to construct an array of maximum length with product of all array elements equal to K, such that each array element except the first one is divisible by its previous adjacent element.Note: Every array element in the generated array must be greater than 1. Examples: In
    7 min read
  • Maximum product from array such that frequency sum of all repeating elements in product is less than or equal to 2 * k
    Given an array arr[] and an integer k, the task is to find the maximum product from the array such that the frequency sum of all repeating elements in the product is ≤ 2 * k, where frequency sum is the sum of frequencies of all the elements in the product that appear more than once. For example, if
    7 min read
  • Maximum size of subset such that product of all subset elements is a factor of N
    Given an integer N and an array arr[] having M integers, the task is to find the maximum size of the subset such that the product of all elements of the subset is a factor of N. Examples: Input: N = 12, arr[] = {2, 3, 4}Output: 2Explanation: The given array 5 subsets such that the product of all ele
    6 min read
  • Minimize cost to split an array into K subsets such that the cost of each element is its product with its position in the subset
    Given an array arr[] of size N and a positive integer K, the task is to find the minimum possible cost to split the array into K subsets, where the cost of ith element ( 1-based indexing ) of each subset is equal to the product of that element and i. Examples: Input: arr[] = { 2, 3, 4, 1 }, K = 3 Ou
    7 min read
  • Maximum number of subsets an array can be split into such that product of their minimums with size of subsets is at least K
    Given an array arr[] consisting of N integers and an integer K, the task is to find the maximum number of disjoint subsets that the given array can be split into such that the product of the minimum element of each subset with the size of the subset is at least K. Examples: Input: arr[] = {7, 11, 2,
    8 min read
  • Split array into equal length subsets with maximum sum of Kth largest element of each subset
    Given an array arr[] of size N, two positive integers M and K, the task is to partition the array into M equal length subsets such that the sum of the Kth largest element of all these subsets is maximum. If it is not possible to partition the array into M equal length subsets, then print -1. Example
    7 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