Maximize the size of array by deleting exactly k sub-arrays to make array prime

Given an array arr[] of N positive integers and a non negative integer K. The task is to delete exactly K sub-arrays from the array such that all the remaining elements of the array are prime and the size of the remaining array is maximum possible.

Examples:

Input: arr[] = {2, 4, 2, 2, 4, 2, 4, 2}, k = 2
Output: 4
Delete the subarrays arr[1] and arr[4…6] and
the remaining prime array will be {2, 2, 2, 2}

Input: arr[] = {2, 4, 2, 2, 4, 2, 4, 2}, k = 3
Output: 5

A simple approach would be to search in all the sub-arrays that would cost us O(N2) time complexity and then keep track of the number of primes or composites in particular length of sub-array.

An efficient approach is to keep the track of number of primes between two consecutive composites.

  1. Preprocessing step: Store all the primes in prime array using Sieve of Eratosthenes
  2. Compute the indices of all composite numbers in a vector v.
  3. Compute the distance between two consecutive indices of above described vector in a vector diff as this will store the number of primes between any two consecutive composites.
  4. Sort this vector. After sorting we get the subarray that contain least no of primes to highest no of primes.
  5. Compute the prefix sum of this vector. Now each index of diff denotes the k value and value in diff denotes no of primes to be deleted when deleting k subarrays. 0th index denotes the largest k less than size of v, 1st index denotes second largest k and so on. So, from prefix sum vector we directly get the no of primes to be deleted.

After performing the above steps our solution depends on three cases:

  1. This is impossible case if k is 0 and there are composite integers in the array.
  2. If k is greater than or equal to no of composites then we can delete all composite integers and extra primes to equate the value k.These all subarrays are of size 1 which gives us optimal answer.
  3. If k is less than no of composite integers then we have to delete those subarrays which contain all the composite and no of primes falling in these subarrays.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
const int N = 1e7 + 5;
bool prime[N];
  
// Sieve of Eratosthenes
void seive()
{
    for (int i = 2; i < N; i++) {
        if (!prime[i]) {
            for (int j = i + i; j < N; j += i) {
                prime[j] = 1;
            }
        }
    }
    prime[1] = 1;
}
  
// Function to return the size
// of the maximized array
int maxSizeArr(int* arr, int n, int k)
{
    vector<int> v, diff;
  
    // Insert the indices of composite numbers
    for (int i = 0; i < n; i++) {
        if (prime[arr[i]])
            v.push_back(i);
    }
  
    // Compute the number of prime between
    // two consecutive composite
    for (int i = 1; i < v.size(); i++) {
        diff.push_back(v[i] - v[i - 1] - 1);
    }
  
    // Sort the diff vector
    sort(diff.begin(), diff.end());
  
    // Compute the prefix sum of diff vector
    for (int i = 1; i < diff.size(); i++) {
        diff[i] += diff[i - 1];
    }
  
    // Impossible case
    if (k > n || (k == 0 && v.size())) {
        return -1;
    }
  
    // Delete sub-arrays of length 1
    else if (v.size() <= k) {
        return (n - k);
    }
  
    // Find the number of primes to be deleted
    // when deleting the sub-arrays
    else if (v.size() > k) {
        int tt = v.size() - k;
        int sum = 0;
        sum += diff[tt - 1];
        int res = n - (v.size() + sum);
        return res;
    }
}
  
// Driver code
int main()
{
    seive();
    int arr[] = { 2, 4, 2, 2, 4, 2, 4, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 2;
    cout << maxSizeArr(arr, n, k);
  
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python implementation of above approach
  
N = 10000005
prime = [False]*N
  
# Sieve of Eratosthenes
def seive():
    for i in range(2,N):
        if not prime[i]:
            for j in range(i+1,N):
                prime[j] = True
      
    prime[1] = True
  
# Function to return the size
# of the maximized array
def maxSizeArr(arr, n, k):
    v, diff = [], []
  
    # Insert the indices of composite numbers
    for i in range(n):
        if prime[arr[i]]:
            v.append(i)
      
    # Compute the number of prime between
    # two consecutive composite
    for i in range(1, len(v)):
        diff.append(v[i] - v[i-1] -1)
      
    # Sort the diff vector
    diff.sort()
  
    # Compute the prefix sum of diff vector
    for i in range(1, len(diff)):
        diff[i] += diff[i-1]
      
    # Impossible case
    if k > n or (k == 0 and len(v)):
        return -1
      
    # Delete sub-arrays of length 1
    elif len(v) <= k:
        return (n-k)
      
    # Find the number of primes to be deleted
    # when deleting the sub-arrays
    elif len(v) > k:
        tt = len(v) - k
        s = 0
        s += diff[tt-1]
        res = n - (len(v) + s)
        return res
  
  
# Driver code
if __name__ == "__main__":
      
    seive()
  
    arr = [2, 4, 2, 2, 4, 2, 4, 2]
    n = len(arr)
    k = 2
  
    print(maxSizeArr(arr, n, k)) 
  
# This code is contributed by
# sanjeev2552 

chevron_right


Output:

4


My Personal Notes arrow_drop_up

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.



Improved By : sanjeev2552