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