![]() |
VOOZH | about |
Given two integer values N and K, the task is to create an array A of N integers such that number of the total positive sum subarrays is exactly K and the remaining subarrays have a negative sum
(-1000 ≤ A[i] ≤ 1000).
Examples:
Input: N = 4, K=5
Output: 2 2 -1 -1000
Explanation:
Positive Sum Subarrays: [2] [2] [2, 2] [2, -1] [2, 2, -1]
Negative Sum Subarrays: [-1] [-1000] [-1, -1000], [2, 2, -1, -1000], [2, -1, -1000]Input: N = 5, K=7
Output: 2 2 2 -5 -1000
Explanation:
Positive Sum Subarrays: [2] [2] [2] [2, 2] [2, 2] [2, 2, 2] [2, 2, 2, -5]
Negative Sum Subarrays: [-5] [-1000] [-5, -1000], [2, -5] [2, 2, -5], [2, -5, -1000], [2, 2, -5, -1000], [2, 2, 2, -5, -1000]
Approach: To solve the problem follow the below idea:
Calculate the number of positive integers needed to form K positive subarrays by iterating from 0 to n-1, and for each value if the number i*(i+1)/2 is greater than K, it needs i positive numbers to form exactly K positive subarrays. Now calculate the number of extra subarrays that must have positive sums by subtracting the number of positive subarrays we have already added, from K. This gives the number of additional subarrays that must have positive sums. Now, fill the remaining elements of the array. For each element, check if we need to add a negative number to form an additional positive subarray, calculate the value of the negative number based on how many additional subarrays we need to form, and then adds it to the array. If we don't, it adds a large negative number (-1000) to the array to ensure that all remaining subarrays have negative sums.
Below are the steps for the above approach:
Below is the code for the above approach:
2 2 -1 -1000
Time Complexity: O(n)
Auxiliary Space: O(n)