You are given two integers N and M (M ≤ N), the task is to create an array of length N following the below-given conditions.
- |Ai| = i, Formally, A[i] will be either -i or i.
- Exactly M prefix arrays should be there, Such that sum of each prefix array should be greater than zero.
Note: If there are multiple arrangements, then output any valid arrangement.
Examples:
Input: N = 3, M = 3
Output: 1 2 3
Explanation: There are Exactly 3 prefix arrays having sum greater than zero, Which are:
First prefix arr[] : {1}, Sum=1
Second prefix arr[] 1: {1, 2}, Sum=1+2=3
Third prefix arr[] = {1, 2, 3}, Sum=1+2+3=6
It can be verified that the output arrangement follows all the constraints provided in the problem statement.
Input: N = 4, M = 2
Output: 1 -2 3 -4
Explanation: There are exactly 2 prefix arrays having sum greater than zero, Which are {1} and {1, -2, 3} having sum 1 and 2 respectively.
Approach: The problem can be solved based on the following observation
Try to keep the odd positioned elements positive and even positioned elements as negative and maintain count of positive prefixes(If the required number of positive sum prefix is at most N/2). Otherwise, place positive elements till the required number of positive prefix becomes less than the remaining array size.
Follow these steps to solve the problem:
- Create a StringBuilder type ans and int type count variable for arrangement.
- Run a loop from i = 1 to N and follow the below-mentioned steps inside the loop's scope:
- If M is at most N/2:
- If i is odd and count < M, append i in ans and increment counter else append -i.
- Otherwise, do the following:
- If i is odd and count < N-M append -i in ans and increment counter else append i.
- Print ans.
Below is the implementation of the above approach.
Time Complexity: O(N)
Auxiliary Space: O(N)
Another Approach:
- Create a function solve that takes in two integers n and m and returns a vector of integers.
- Create a vector arr of size n.
- Initialize a counter variable count to 0.
- Loop through the indices of arr from 0 to n-1.
- Check if count is less than m.
- If count is less than m, check if the current index is even.
- If the current index is even, set the value at that index in arr to i+1.
- If the current index is odd, set the value at that index in arr to -(i+1) and increment count.
- If count is greater than or equal to m, check if the current index is even.
- If the current index is even, set the value at that index in arr to -(i+1).
- If the current index is odd, set the value at that index in arr to i+1.
- Return arr.
- In the main function, call solve with the inputs n and m.
- Loop through the elements in the returned vector and print each element followed by a space.
- Print a newline character to finish the output.
Time Complexity: O(n)
Auxiliary Space: O(1)
Related Articles: