Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Rearrange the array to maximize the number of primes in prefix sum of the array

  • Last Updated : 12 May, 2021

Given an array arr[] of 1’s and 2’s, the task is to re-arrange the array in such a way that the prefix sum of the rearranged array has the maximum number of primes. Note that there can be multiple answers to it. 
Examples: 
 

Input: arr[] = {1, 2, 1, 2, 1} 
Output: 2 1 1 1 2 
The prefix sum array is {2, 3, 4, 5, 7} which has {2, 3, 5, 7} as primes 
which is the maximum possible. 
Input: arr[] = {1, 1, 2, 1, 1, 1, 2, 1, 1} 
Output: 2 1 1 1 1 1 1 1 2 
 

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

 

Approach: The problem can be solved with two observations, one is the first prime is 2, and all other primes after that are odd numbers (All odd numbers are not prime). Hence simply fill the first position with 2 if there are any, and then fill an odd number of ones, and then fill the remaining 2’s. At the end insert the only 1 left (if the initial number of ones were even).
In doing so, we start from 2 and end at an odd number by adding an odd number of 1’s and then by adding 2’s to it, we jump from an odd number to another odd number which maximizes the probability of primes. 
Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the re-arranged array
void solve(int a[], int n)
{
    int ones = 0, twos = 0;
 
    // Count the number of
    // ones and twos in a[]
    for (int i = 0; i < n; i++) {
 
        // If the array element is 1
        if (a[i] == 1)
            ones++;
 
        // Array element is 2
        else
            twos++;
    }
    int ind = 0;
 
    // If it has at least one 2
    // Fill up first 2
    if (twos)
        a[ind++] = 2;
 
    // Decrease the cnt of
    // ones if even
    bool evenOnes = (ones % 2 == 0) ? true : false;
    if (evenOnes)
        ones -= 1;
 
    // Fill up with odd count of ones
    for (int i = 0; i < ones; i++)
        a[ind++] = 1;
 
    // Fill up with remaining twos
    for (int i = 0; i < twos - 1; i++)
        a[ind++] = 2;
 
    // If even ones, then fill last position
    if (evenOnes)
        a[ind++] = 1;
 
    // Print the rearranged array
    for (int i = 0; i < n; i++)
        cout << a[i] << " ";
}
 
// Driver code
int main()
{
    int a[] = { 1, 2, 1, 2, 1 };
    int n = sizeof(a) / sizeof(a[0]);
    solve(a, n);
 
    return 0;
}

Java




// Java implementation of the approach
import java.io.*;
 
class GFG {
 
    // Function to print the re-arranged array
    static void solve(int a[], int n)
    {
        int ones = 0, twos = 0;
 
        // Count the number of
        // ones and twos in a[]
        for (int i = 0; i < n; i++) {
 
            // If the array element is 1
            if (a[i] == 1)
                ones++;
 
            // Array element is 2
            else
                twos++;
        }
        int ind = 0;
 
        // If it has at least one 2
        // Fill up first 2
        if (twos > 0)
            a[ind++] = 2;
 
        // Decrease the cnt of
        // ones if even
        boolean evenOnes = (ones % 2 == 0) ? true : false;
        if (evenOnes)
            ones -= 1;
 
        // Fill up with odd count of ones
        for (int i = 0; i < ones; i++)
            a[ind++] = 1;
 
        // Fill up with remaining twos
        for (int i = 0; i < twos - 1; i++)
            a[ind++] = 2;
 
        // If even ones, then fill last position
        if (evenOnes)
            a[ind++] = 1;
 
        // Print the rearranged array
        for (int i = 0; i < n; i++)
            System.out.print(a[i] + " ");
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        int a[] = { 1, 2, 1, 2, 1 };
        int n = a.length;
        solve(a, n);
    }
}
 
// This code is contributed by ajit.

Python




# Python3 implementation of the approach
 
# Function to print the re-arranged array
def solve(a, n):
 
    ones, twos = 0, 0
 
    # Count the number of
    # ones and twos in a[]
    for i in range(n):
 
        # If the array element is 1
        if (a[i] == 1):
            ones+=1
 
        # Array element is 2
        else:
            twos+=1
 
    ind = 0
 
    # If it has at least one 2
    # Fill up first 2
    if (twos):
        a[ind] = 2
        ind+=1
 
    # Decrease the cnt of
    # ones if even
    if ones % 2 == 0:
        evenOnes = True
    else:
        evenOnes = False
 
 
    if (evenOnes):
        ones -= 1
 
    # Fill up with odd count of ones
    for i in range(ones):
        a[ind] = 1
        ind += 1
 
 
    # Fill up with remaining twos
    for i in range(twos-1):
        a[ind] = 2
        ind += 1
 
    # If even ones, then fill last position
    if (evenOnes):
        a[ind] = 1
        ind += 1
 
    # Print the rearranged array
    for i in range(n):
        print(a[i],end = " ")
 
# Driver code
 
a = [1, 2, 1, 2, 1]
n = len(a)
solve(a, n)
 
# This code is contributed by mohit kumar 29

C#




// C# implementation of the approach
using System;
 
class GFG
{
     
    // Function to print the re-arranged array
    static void solve(int []a, int n)
    {
        int ones = 0, twos = 0;
 
        // Count the number of
        // ones and twos in a[]
        for (int i = 0; i < n; i++)
        {
 
            // If the array element is 1
            if (a[i] == 1)
                ones++;
 
            // Array element is 2
            else
                twos++;
        }
        int ind = 0;
 
        // If it has at least one 2
        // Fill up first 2
        if (twos > 0)
            a[ind++] = 2;
 
        // Decrease the cnt of
        // ones if even
        bool evenOnes = (ones % 2 == 0) ? true : false;
        if (evenOnes)
            ones -= 1;
 
        // Fill up with odd count of ones
        for (int i = 0; i < ones; i++)
            a[ind++] = 1;
 
        // Fill up with remaining twos
        for (int i = 0; i < twos - 1; i++)
            a[ind++] = 2;
 
        // If even ones, then fill last position
        if (evenOnes)
            a[ind++] = 1;
 
        // Print the rearranged array
        for (int i = 0; i < n; i++)
            Console.Write(a[i] + " ");
    }
 
    // Driver code
    static public void Main ()
    {
        int []a = { 1, 2, 1, 2, 1 };
        int n = a.Length;
        solve(a, n);
    }
}
 
// This code is contributed by Tushil.

PHP




<?php
// PHP implementation of the approach
 
// Function to print the re-arranged array
function solve($a, $n)
{
    $ones = 0; $twos = 0;
 
    // Count the number of
    // ones and twos in a[]
    for ($i = 0; $i < $n; $i++)
    {
 
        // If the array element is 1
        if ($a[$i] == 1)
            $ones++;
 
        // Array element is 2
        else
            $twos++;
    }
    $ind = 0;
 
    // If it has at least one 2
    // Fill up first 2
    if ($twos)
        $a[$ind++] = 2;
 
    // Decrease the cnt of
    // ones if even
    $evenOnes = ($ones % 2 == 0) ? true : false;
    if ($evenOnes)
        $ones -= 1;
 
    // Fill up with odd count of ones
    for ($i = 0; $i < $ones; $i++)
        $a[$ind++] = 1;
 
    // Fill up with remaining twos
    for ($i = 0; $i < $twos - 1; $i++)
        $a[$ind++] = 2;
 
    // If even ones, then fill last position
    if ($evenOnes)
        $a[$ind++] = 1;
 
    // Print the rearranged array
    for ($i = 0; $i < $n; $i++)
        echo $a[$i], " ";
}
 
// Driver code
$a = array( 1, 2, 1, 2, 1 );
$n = count($a);
solve($a, $n);
 
// This code is contributed by AnkitRai01
 
?>

Javascript




<script>
    // Javascript implementation of the approach
     
    // Function to print the re-arranged array
    function solve(a, n)
    {
        let ones = 0, twos = 0;
   
        // Count the number of
        // ones and twos in a[]
        for (let i = 0; i < n; i++)
        {
   
            // If the array element is 1
            if (a[i] == 1)
                ones++;
   
            // Array element is 2
            else
                twos++;
        }
        let ind = 0;
   
        // If it has at least one 2
        // Fill up first 2
        if (twos > 0)
            a[ind++] = 2;
   
        // Decrease the cnt of
        // ones if even
        let evenOnes = (ones % 2 == 0) ? true : false;
        if (evenOnes)
            ones -= 1;
   
        // Fill up with odd count of ones
        for (let i = 0; i < ones; i++)
            a[ind++] = 1;
   
        // Fill up with remaining twos
        for (let i = 0; i < twos - 1; i++)
            a[ind++] = 2;
   
        // If even ones, then fill last position
        if (evenOnes)
            a[ind++] = 1;
   
        // Print the rearranged array
        for (let i = 0; i < n; i++)
            document.write(a[i] + " ");
    }
     
    let a = [ 1, 2, 1, 2, 1 ];
    let n = a.length;
    solve(a, n);
     
</script>
Output: 
2 1 1 1 2

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!