Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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 
 

 

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. 

Algorithm:

Step 1: Initialize two variables ones and twos to 0 to count the number of “ones” and “twos” in the input array.
Step 2: Loop through the input array a from index 0 to n-1.
             a. If the current element at index i is 1, increment “ones” by 1. Otherwise, if the current element is 2, increment “twos” by 1.
Step 3: In order to maintain track of the current index of the rearranged array, initialise the index variable “ind” to 0.
Step 4: If there is at least one 2 in the input array, set the first element of the rearranged array to 2 and increment “ind” by 1.
Step 5: See if there are more even or fewer odd “ones” than ones. Subtract one from “ones” and set the boolean variable evenOnes to true if the                  result is even. In any other case, set “evenOnes” to false.
Step 6: Fill up the rearranged array with ones until the count of “ones” becomes odd.
Step 7: Fill up the rearranged array with “twos” except for the last position.
Step 8: Set the final element of the rearranged array to 1 if “evenOnes” is true.
Step 9: Print the rearranged array.

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

 

Time Complexity: O(n), where n is the size of the given array
Auxiliary Space: O(1), as no extra space is used



Last Updated : 25 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads