Given an integer N(3 ≤ N ≤ 105), the task is to generate an array of N distinct positive elements such that the count and sum of elements of both parties i.e even and odd, are the same. If it is not possible to construct such an array, print -1.
Input: N = 8 Output: 2, 4, 6, 8, 1, 3, 5, 11
Input: 6 Output: -1 Explanation: For the count of odd and even array elements to be equal, 3 even and odd elements must be present in the array. But, sum of 3 odd elements will always be odd. Therefore, it is not possible to generate such an array.
Approach: Follow the steps below to solve the problem:
If N is odd or (N / 2) is odd, then print -1.
Print N/2 even values starting from 2 and store the count in some variable, say SumEven.
Print N / 2 – 1 odd values starting from 1 and store the sum in another variable, say SumOdd.
At last print SumEven – SumOdd which is also odd.
Below is the implementation of the above approach:
Please Login to comment...