Open In App

Subarray with exactly K positive sum

Last Updated : 18 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
void postiveSubarray(int n, int k)
{
 
    int pos_sub = k;
 
    // Calculate number of positive
    // elements to be added in array
    int pos = 0;
    for (int i = 0; i < n; i++) {
        if ((i * (i + 1)) / 2 > k) {
            break;
        }
        pos = i;
    }
 
    // Print positive elements
    for (int i = 0; i < pos; i++) {
        cout << 2 << " ";
    }
 
    // Calculate number of extra subarrays
    // with positive sum
    int extra = k - ((pos * (pos + 1)) / 2);
 
    // Print remaining elements of array
    for (int i = 0; i < n - pos; i++) {
        if (extra > 0) {
 
            // If there are still extra
            // subarrays with positive sum,
            // add a negative number such
            // that the sum of subarray
            // becomes positive
            int num = pos - extra + 1;
            num = -(num * 2 - 1);
            cout << num << " ";
            extra = 0;
            continue;
        }
 
        // Otherwise, print a large
        // negative number
        cout << -1000 << " ";
    }
 
    cout << endl;
    return;
}
 
// Drivers code
int main()
{
    int n = 4;
    int k = 5;
 
    // Function Call
    postiveSubarray(n, k);
    return 0;
}


Java




// Java code for the above approach:
 
import java.io.*;
 
class GFG {
 
    static void positiveSubarray(int n, int k)
    {
        int pos_sub = k;
 
        // Calculate number of positive elements to be added
        // in array
        int pos = 0;
        for (int i = 0; i < n; i++) {
            if ((i * (i + 1)) / 2 > k) {
                break;
            }
            pos = i;
        }
 
        // print positive elements
        for (int i = 0; i < pos; i++) {
            System.out.print(2 + " ");
        }
 
        // calculate number of extra subarrays with positive
        // sum
        int extra = k - ((pos * (pos + 1)) / 2);
 
        // Print remaining elements of array
        for (int i = 0; i < n - pos; i++) {
            if (extra > 0) {
                // If there are still extra subarray with
                // positive sum, add a negative number such
                // that the sum of subarray becomes positive
                int num = pos - extra + 1;
                num = -(num * 2 - 1);
                System.out.print(num + " ");
                extra = 0;
                continue;
            }
            // Otherwise, print a large negative number
            System.out.print(-1000 + " ");
        }
 
        return;
    }
 
    public static void main(String[] args)
    {
        int n = 4, k = 5;
 
        // FUnction call
        positiveSubarray(n, k);
    }
}
 
// This code is contributed by sankar.


Python3




def positive_subarray(n, k):
    pos_sub = k
 
    # Calculate number of positive
    # elements to be added in array
    pos = 0
    for i in range(n):
        if (i * (i + 1)) // 2 > k:
            break
        pos = i
 
    # Print positive elements
    for i in range(pos):
        print(2, end=" ")
 
    # Calculate number of extra subarrays
    # with positive sum
    extra = k - ((pos * (pos + 1)) // 2)
 
    # Print remaining elements of array
    for i in range(n - pos):
        if extra > 0:
 
            # If there are still extra
            # subarrays with positive sum,
            # add a negative number such
            # that the sum of subarray
            # becomes positive
            num = pos - extra + 1
            num = -(num * 2 - 1)
            print(num, end=" ")
            extra = 0
            continue
 
        # Otherwise, print a large
        # negative number
        print(-1000, end=" ")
 
    print()
 
# Driver code
n = 4
k = 5
 
# Function call
positive_subarray(n, k)


C#




// C# code for the above approach:
 
using System;
 
class GFG {
 
    static void positiveSubarray(int n, int k)
    {
        // Calculate number of positive elements to be added
        // in array
        int pos = 0;
        for (int i = 0; i < n; i++) {
            if ((i * (i + 1)) / 2 > k) {
                break;
            }
            pos = i;
        }
 
        // print positive elements
        for (int i = 0; i < pos; i++) {
            Console.Write(2 + " ");
        }
 
        // calculate number of extra subarrays with positive
        // sum
        int extra = k - ((pos * (pos + 1)) / 2);
 
        // Print remaining elements of array
        for (int i = 0; i < n - pos; i++) {
            if (extra > 0) {
                // If there are still extra subarray with
                // positive sum, add a negative number such
                // that the sum of subarray becomes positive
                int num = pos - extra + 1;
                num = -(num * 2 - 1);
                Console.Write(num + " ");
                extra = 0;
                continue;
            }
            // Otherwise, print a large negative number
            Console.Write(-1000 + " ");
        }
 
        return;
    }
 
    public static void Main()
    {
        int n = 4, k = 5;
 
        // FUnction call
        positiveSubarray(n, k);
    }
}
 
// This code is contributed by Pushpesh Raj


Javascript




function postiveSubarray(n, k) {
    let pos_sub = k;
     
    // Calculate number of positive
    // elements to be added in array
    let pos = 0;
    for (let i = 0; i < n; i++) {
        if ((i * (i + 1)) / 2 > k) {
            break;
        }
        pos = i;
    }
     
    // Print positive elements
    for (let i = 0; i < pos; i++) {
        console.log(2 + " ");
    }
     
    // Calculate number of extra subarrays
    // with positive sum
    let extra = k - ((pos * (pos + 1)) / 2);
     
    // Print remaining elements of array
    for (let i = 0; i < n - pos; i++) {
        if (extra > 0) {
         
         
            // If there are still extra
            // subarrays with positive sum,
            // add a negative number such
            // that the sum of subarray
            // becomes positive
            let num = pos - extra + 1;
            num = -(num * 2 - 1);
            console.log(num + " ");
            extra = 0;
            continue;
        }
         
        // Otherwise, print a large
        // negative number
        console.log(-1000 + " ");
    }
    console.log("\n");
    return;
}
 
// Drivers code
let n = 4;
let k = 5;
postiveSubarray(n, k);
return 0;


Output

2 2 -1 -1000 





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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads