VOOZH about

URL: https://www.geeksforgeeks.org/dsa/subarray-with-exactly-k-positive-sum/

⇱ Subarray with exactly K positive sum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Subarray with exactly K positive sum

Last Updated : 18 Sep, 2023

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:

  • Initialize a variable pos to keep track of the number of positive integers that need to be added to form exactly k positive-sum subarrays.
  • Calculate the number of positive elements to be added to the array, run a loop from index 0 to n - 1, and for each value if the number i*(i+1)/2 is greater than k, update pos = i.
  • Run a loop from index 0 to pos - 1 and print 2 as the first pos elements of the resultant array.
  • Initialize a variable extra and calculate the number of extra positive subarrays needed to reach the target of k positive subarrays,
    • extra = k - ((pos * (pos + 1)) / 2).
  • Check if extra > 0, add a negative number such that the sum of the subarray becomes positive,
    • num = pos - extra + 1, num = -(num * 2 - 1)
    • else print a large negative number.

Below is the code for the above approach:


Output
2 2 -1 -1000 

Time Complexity: O(n)
Auxiliary Space: O(n)

Comment
Article Tags: