Rearrange the array to maximize the number of primes in prefix sum of the array | Function to print the re - arranged array ; Count the number of ones and twos in a [ ] ; If the array element is 1 ; Array element is 2 ; If it has at least one 2 Fill up first 2 ; Decrease the cnt of ones if even ; Fill up with odd count of ones ; Fill up with remaining twos ; If even ones , then fill last position ; Print the rearranged array ; Driver code
def solve ( a , n ) : NEW_LINE INDENT ones , twos = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] == 1 ) : NEW_LINE INDENT ones += 1 NEW_LINE DEDENT else : NEW_LINE INDENT twos += 1 NEW_LINE DEDENT DEDENT ind = 0 NEW_LINE if ( twos ) : NEW_LINE INDENT a [ ind ] = 2 NEW_LINE ind += 1 NEW_LINE DEDENT if ones % 2 == 0 : NEW_LINE INDENT evenOnes = True NEW_LINE DEDENT else : NEW_LINE INDENT evenOnes = False NEW_LINE DEDENT if ( evenOnes ) : NEW_LINE INDENT ones -= 1 NEW_LINE DEDENT for i in range ( ones ) : NEW_LINE INDENT a [ ind ] = 1 NEW_LINE ind += 1 NEW_LINE DEDENT for i in range ( twos - 1 ) : NEW_LINE INDENT a [ ind ] = 2 NEW_LINE ind += 1 NEW_LINE DEDENT if ( evenOnes ) : NEW_LINE INDENT a [ ind ] = 1 NEW_LINE ind += 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( a [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT a = [ 1 , 2 , 1 , 2 , 1 ] NEW_LINE n = len ( a ) NEW_LINE solve ( a , n ) NEW_LINE