Construct a distinct elements array with given size, sum and element upper bound

Given N size of the original array, SUM total sum of all elements present in the array and K such that no element in array is greater than K, construct the original array where all elements in the array are unique. If there is no solution, print “Not Possible”.
Note : All elements should be positive.

Examples:

Input : N = 3, SUM = 15, K = 8  
Output: array[] = {1, 6, 8} 
The constructed array has size 3, sum
15 and all elements are smaller than
or equal to 8.

Input : N = 2,  SUM = 9, K = 10  
Output: array[]={1, 8} 

Input  : N = 3, SUM = 23, K = 8  
Output : Not Possible

We must choose N elements and all elements must be positive and no element should be greater than K. Since elements are positive and distinct, smallest possible sum is equal to sum of first N natural numbers which is N * (N + 1)/2.
Since all elements should be smaller than or equal to K, largest possible sum is K + (K-1) + (K-2) + ….. + (K-N+1) = (N*K)- (N*(N-1))/2.

So if the given sum is in between smallest and largest possible sum then only the array can be formed, or else we have to print -1.

Following is the complete algorithm if it is feasible to construct the array.

1. Create an array of size N and fill it with first N numbers. So total sum of the array will be smallest possible sum.
2. Find the largest element of the array, but as the array is sorted so array[N] will be largest.

  • If the largest element is less than K, we replace it with K and check the new sum of the array.
    • If it is less than given SUM, we move to N-1 position in the array because array[N] can’t be further incremented and to maintain uniqueness we decrease K by 1.
    • If it is greater than given SUM, we replace an element such that sum will be given SUM, and will come out of loop.
  • If the largest element is equal to K, we move to N-1 position in the array because array[N] can’t be further incremented and to maintain uniqueness we will decrease K by 1.

3. Print the array.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to construct a distinct element
// array with given size, sum, element upper
// bound and all elements positive
#include <bits/stdc++.h>
using namespace std;
  
void printArray(int N, int SUM, int K)
{
    // smallest possible sum
    int minSum = (N * (N + 1)) / 2;
  
    // largest possible sum
    int maxSum = (N * K) - (N * (N - 1)) / 2;
  
    if (minSum > SUM || maxSum < SUM) {
        printf("Not Possible");
        return;
    }
  
    // Creating array with minimum possible
    // sum.
    int arr[N + 1];
    for (int i = 1; i <= N; i++)
        arr[i] = i;
    int sum = minSum;
  
    // running the loop from last because the
    // array is sorted and running from last
    // will give largest numbers
    for (int i = N; i >= 1; i--) {
  
        // replacing i with K, Note arr[i] = i
        int x = sum + (K - i);
        if (x < SUM) {
            sum = sum + (K - i);
            arr[i] = K; // can't be incremented further
            K--; // to maintain uniqueness
        }
  
        else {
  
            // directly replacing with a suitable
            // element to make sum as given sum
            arr[i] += (SUM - sum);
            sum = SUM;
            break;
        }
    }
  
    for (int i = 1; i <= N; i++)
        cout << arr[i] << " ";
}
  
// Driver code
int main()
{
    int N = 3, SUM = 15, K = 8;
    printArray(N, SUM, K);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to construct a distinct element
// array with given size, sum, element upper
// bound and all elements positive
  
import java.io.*;
  
class GFG {
    static void printArray(int N, int SUM, int K)
    {
        // smallest possible sum
        int minSum = (N * (N + 1)) / 2;
  
        // largest possible sum
        int maxSum = (N * K) - (N * (N - 1)) / 2;
  
        if (minSum > SUM || maxSum < SUM) {
            System.out.println("Not Possible");
            return;
        }
  
        // Creating array with
        // minimum possible sum.
        int arr[] = new int[N + 1];
        for (int i = 1; i <= N; i++)
            arr[i] = i;
  
        int sum = minSum;
  
        // running the loop from last because the
        // array is sorted and running from last
        // will give largest numbers
        for (int i = N; i >= 1; i--) {
  
            // replacing i with K, Note arr[i] = i
            int x = sum + (K - i);
            if (x < SUM) {
                sum = sum + (K - i);
  
                // can't be incremented further
                arr[i] = K;
  
                // to maintain uniqueness
                K--;
            }
  
            else {
  
                // directly replacing with a suitable
                // element to make sum as given sum
                arr[i] += (SUM - sum);
                sum = SUM;
                break;
            }
        }
  
        for (int i = 1; i <= N; i++)
            System.out.print(arr[i] + " ");
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int N = 3, SUM = 15, K = 8;
        printArray(N, SUM, K);
    }
}
  
// This code is contributed by vt_m

chevron_right


Python3

# Python 3 program to construct a distinct
# element array with given size, sum,
# element upper bound and all elements
# positive
def printArray(N, SUM, K):

# smallest possible sum
minSum = (N * (N + 1)) / 2

# largest possible sum
maxSum = (N * K) – (N * (N – 1)) / 2

if (minSum > SUM or maxSum < SUM): print("Not Possible") return # Creating array with minimum # possible sum. arr = [0 for i in range(N + 1)] for i in range(1, N + 1, 1): arr[i] = i sum = minSum # running the loop from last because # the array is sorted and running # from last will give largest numbers i = N while(i >= 1):

# replacing i with K, Note arr[i] = i
x = sum + (K – i)
if (x < SUM): sum = sum + (K - i) arr[i] = K # can't be incremented further K -= 1 # to maintain uniqueness else: # directly replacing with a suitable # element to make sum as given sum arr[i] += (SUM - sum) sum = SUM break i -= 1 for i in range(1, N + 1, 1): print(int(arr[i]), end = " ") # Driver code if __name__ == '__main__': N = 3 SUM = 15 K = 8 printArray(N, SUM, K) # This code is contributed by # Surendra_Gangwar [tabby title="C#"]

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to construct a distinct element
// array with given size, sum, element upper
// bound and all elements positive
using System;
  
class GFG {
      
    static void printArray(int N, int SUM, int K)
    {
          
        // smallest possible sum
        int minSum = (N * (N + 1)) / 2;
  
        // largest possible sum
        int maxSum = (N * K) - (N * (N - 1)) / 2;
  
        if (minSum > SUM || maxSum < SUM) {
            Console.WriteLine("Not Possible");
            return;
        }
  
        // Creating array with
        // minimum possible sum.
        int[] arr = new int[N + 1];
        for (int i = 1; i <= N; i++)
            arr[i] = i;
  
        int sum = minSum;
  
        // running the loop from last because the
        // array is sorted and running from last
        // will give largest numbers
        for (int i = N; i >= 1; i--) {
  
            // replacing i with K, Note arr[i] = i
            int x = sum + (K - i);
          
              
            if (x < SUM) {
                sum = sum + (K - i);
  
                // can't be incremented further
                arr[i] = K;
  
                // to maintain uniqueness
                K--;
            }
  
            else {
  
                // directly replacing with a suitable
                // element to make sum as given sum
                arr[i] += (SUM - sum);
                sum = SUM;
                break;
            }
        }
  
        for (int i = 1; i <= N; i++)
            Console.Write(arr[i] + " ");
    }
  
    // Driver code
    public static void Main()
    {
          
        int N = 3, SUM = 15, K = 8;
          
        printArray(N, SUM, K);
    }
}
  
// This code is contributed by vt_m.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to construct a distinct element
// array with given size, sum, element upper
// bound and all elements positive
  
  
function printArray($N, $SUM, $K)
{
    // smallest possible sum
    $minSum = ($N * ($N + 1)) / 2;
  
    // largest possible sum
    $maxSum = ($N * $K) - ($N * ($N - 1)) / 2;
  
    if ($minSum > $SUM || $maxSum < $SUM) {
        echo"Not Possible";
        return;
    }
  
    // Creating array with minimum possible
    // sum.
     $arr = array();
    for ($i = 1; $i <= $N; $i++)
        $arr[$i] = $i;
      $sum = $minSum;
  
    // running the loop from last because the
    // array is sorted and running from last
    // will give largest numbers
    for ($i = $N; $i >= 1; $i--) {
  
        // replacing i with K, Note arr[i] = i
        $x = $sum + ($K - $i);
        if ($x <$SUM) {
            $sum = $sum + ($K - $i);
            $arr[$i] =$K; // can't be incremented further
            $K--; // to maintain uniqueness
        }
  
        else {
  
            // directly replacing with a suitable
            // element to make sum as given sum
            $arr[$i] += ($SUM - $sum);
            $sum = $SUM;
            break;
        }
    }
  
    for ($i = 1; $i <= $N; $i++)
        echo $arr[$i] , " ";
}
  
// Driver code
    $N = 3; $SUM = 15;$K = 8;
    printArray($N, $SUM, $K);
// This code is contributed by inder_verma..
  
?>

chevron_right



Output:

1 6 8

Time Complexity : O(N)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.





Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.