Open In App

Generate an array of given size with equal count and sum of odd and even numbers

Given an integer N, the task is to find an array of length N that contains same count of odd and even elements with an equal sum of even and odd elements in the array.
Note: Print -1 if no such array is possible. 
Examples: 
 

Input: N = 4 
Output: 1 2 5 4 
Explanation: 
Even elements of the array – {2, 4}, S(even) = 6 
Odd elements of the array – {1, 5}, S(odd) = 6
Input: N = 6 
Output: -1 
Explanation: 
There are no such array which contains 3 even elements and 3 odd elements with equal sum. 
 



 

Approach: The key observation in the problem is that only the length of an array which is a multiple of 4 can form an array with an equal number of even and odd elements with equal sum. Below is the illustration of the steps: 
 




Article Tags :