[ad_1]
Given an array arr[] of measurement N, the duty is to rely the minimal variety of parts required to be faraway from the given array such that at any time when any pair (arr[i], arr[j]) is picked, the place i != j and 0 ≤ i < j < N, both arr[i] is a number of of arr[j] or vice versa.
Examples:
Enter: N = 5, arr[] = {4, 3, 4, 5, 2}
Output: 2
Rationalization: At the moment, pair (arr[2], arr[3]) doesn’t fulfill given situation.
Equally, with i = 4, and that i =5 as effectively.
Take away arr[2] = 3, and arr[4] = 5, to would make array fulfill given circumstances.
Subsequently minimal elimination of parts is 2. And array is {4, 4, 2}.Enter: N = 3, arr[] = {2, 2, 4}
Output: 0
Rationalization: As, array already satisfies the given situation, there’s no have to take away any ingredient.
Strategy: The issue might be solved through the use of Dynamic Programming and Sieve of Eratosthenes based mostly on the next concept:
Get the frequencies of the array parts. Now discover the ingredient having most variety of multiples current within the array utilizing the frequency desk and dynamic programming. All of the remaining parts needs to be deleted to attain the situation utilizing minimal deletions.
Comply with the steps talked about under to unravel the issue:
- Traverse the arr[] and retailer the utmost ingredient.
- Retailer the frequency of the array parts.
- Traversing via dp array and retailer frequency of ith ingredient in dp[i].
- Then use Sieve of Eratosthenes to traverse via multiples of i.
- Replace the present dp worth with the utmost of dp[i] and present dp worth.
- Discovering the max ingredient in dp[] array after doing operations
Under is the implementation of the above method:
C++
|
Time Complexity: O(M*log(M)), the place M is most ingredient current in given array
Auxiliary Area: O(M)
[ad_2]