Skip to content
Related Articles

Related Articles

Improve Article

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

  • Difficulty Level : Hard
  • Last Updated : 05 Apr, 2021

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++




// 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;
}

Java




// 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

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

C#




// 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.

PHP




<?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..
 
?>

Javascript




<script>
// JavaScript 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
    let minSum = Math.floor((N * (N + 1)) / 2);
 
    // largest possible sum
    let maxSum = (N * K) - Math.floor((N * (N - 1)) / 2);
 
    if (minSum > SUM || maxSum < SUM) {
        document.write("Not Possible");
        return;
    }
 
    // Creating array with minimum possible
    // sum.
    let arr = new Array(N + 1);
    for (let i = 1; i <= N; i++)
        arr[i] = i;
    let sum = minSum;
 
    // running the loop from last because the
    // array is sorted and running from last
    // will give largest numbers
    for (let i = N; i >= 1; i--) {
 
        // replacing i with K, Note arr[i] = i
        let 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 (let i = 1; i <= N; i++)
        document.write(arr[i] + " ");
}
 
// Driver code
    let N = 3, SUM = 15, K = 8;
    printArray(N, SUM, K);
 
// This code is contributed by Surbhi Tyagi.
</script>

Output: 
 

1 6 8

Time Complexity : O(N)
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :