VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-possible-number-in-a-sequence-of-distinct-elements-with-given-average/

⇱ Maximum possible number in a Sequence of distinct elements with given Average - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum possible number in a Sequence of distinct elements with given Average

Last Updated : 23 Jul, 2025

Given integers N and K, the task is to find the maximum possible number an N length sequence of distinct positive integers can have if the average of the elements of the sequence is K.

Examples:

Input: N = 4, K = 3
Output: 6
Explanation: The desired sequence would be - {1, 2, 3, 6}. 
There could be other sequences as well satisfying the given values of N and K, such as {1, 2, 4, 5}.
But , since the maximum possible number in the sequence is needed, 6 would be the answer.

Input: N = 5, K = 4
Output: 10
Explanation: The desired sequence would be - {1, 2, 3, 4, 10}.

Input: N = 5, K = 2
Output: -1
Explanation: Forming a sequence having 5 distinct positive integer and average as 2 is not possible.

Approach: The solution to the problem is based on the following observation:

  • From the number of integers in the sequence and the average of the sequence, the total sum of all numbers of the sequence can be easily calculated by using the following formula: 
    sum of all numbers in sequence = (number of terms) x (average of all terms)
  • Now , suppose the maximum term (or number) is M and sum of the sequence is S. Then, to maximize M, (S-M) must be minimized.
  • Since , the terms must be distinct  and positive, so the series with minimum possible sum would be 1, 2, 3 . . . (N-1).
    Sum of such a sequence of natural numbers can be easily calculated for (N-1) terms , and would be: (N * (N - 1)) /  2.
  • So , the maximum possible integer would be: M = sum of the given sequence - sum of first (N-1) natural numbers.

Follow the steps mentioned below:

  • Calculate the sum of the given sequence.
  • Find the sum of first (N-1) natural numbers.
  • Calculate the maximum possible number from the above observation.
  • If the maximum value is less than N then no such sequence is possible.
  • Otherwise, the maximum value is the required answer.

Below is the implementation of the above approach: 

 
 


Output
10


 

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


 

Comment