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
function solve ( a , n ) { let ones = 0 , twos = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( a [ i ] == 1 ) ones ++ ; else twos ++ ; } let ind = 0 ; if ( twos > 0 ) a [ ind ++ ] = 2 ; let evenOnes = ( ones % 2 == 0 ) ? true : false ; if ( evenOnes ) ones -= 1 ; for ( let i = 0 ; i < ones ; i ++ ) a [ ind ++ ] = 1 ; for ( let i = 0 ; i < twos - 1 ; i ++ ) a [ ind ++ ] = 2 ; if ( evenOnes ) a [ ind ++ ] = 1 ; 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 ) ;