Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Maximum XOR of Two Numbers in an Array | Set 2
Next article icon

Maximum Sum of Array with given MEX

Last Updated : 12 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given 3 integers N, K, and X, the task is to construct an array arr[] with the below conditions:

  • Size of the array = N
  • MEX of the array = K
  • All array elements should be at most X

Among all the array that follows the above condition print the one having the maximum sum of its elements or print -1 if no such array exists.

Constraints:

  • 1<= N <= 100000
  • 1<= K <= 100000
  • 1<= X <= 100000

Examples:

Input: N=5, K=3, X=3
Output: [0, 1, 2, 2, 2]
Explanation: The MEX of the above array is 3, and sum of its element is 7, it is guaranteed that we cannot create an array having sum greater than 7

Input: N=4, K=7, X=5
Output: -1
Explanation: No valid array exists

Approach: The problem can be solved using the following approach:

Case 1: If min(N, X+1) < K, then answer does not exists i.e. answer = -1.
Reason:

  • If N < K, then the maximum value of MEX that can be created using N numbers is equal to N. For example, if N=4, then arr[] = [0, 1, 2, 3] gives MEX = 4. Therefore, if N<K we cannot achieve MEX = K
  • If X+1 < K, then also it would be impossible to achieve MEX = K due to the fact that for MEX = K, K - 1 should be present in the array, but X is the maximum number present in the array.

Case 2: If answer exists, and we want to maximize it.

Since we have to form MEX=K therefore it is necessary for all the elements from 0 to K-1 to appear at least once in the array. Now since our task is to maximize the sum, all the elements form 0 to K-1 should occur exactly once all the remaining elements will depend upon the value of X i.e.

  • If X = K, then all the remaining values should be K-1 so that MEX = K is preserved
  • If X ≠ K, then all the remaining values should be X.

Steps to solve the problem:

  • If N < K or X + 1 < K, then the answer does not exist, so print -1.
  • Else, since we want the MEX to be equal to K so push all the numbers from 0 to K-1 into our answer.
  • After pushing number from 0 to K-1, check if we can push X as all the remaining elements.
    • If yes, then push all the remaining elements as X.
    • Else, push all the remaining elements as X - 1.
  • Finally, print the answer array.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h> #define ll long long using namespace std; void resultArray(ll N, ll K, ll X) {     // case when answer does not exist     if (N < K || X + 1 < K) {         cout << -1 << endl;         return;     }      // vector to store the answer     vector<ll> ans;     // Push all the numbers less than K into     // the answer, to get MEX = K     for (ll i = 0; i < K; i++) {         ans.push_back(i);     }      // If MEX is equal to maximum element allowed, then fill     // the remaining positions with second maximum element     if (X == K) {         for (int i = K; i < N; i++) {             ans.push_back(K - 1);         }     }     // Else fill the remaining positions with the maximum     // element allowed     else {         for (int i = K; i < N; i++) {             ans.push_back(X);         }     }     for (int i = 0; i < N; i++)         cout << ans[i] << " ";     cout << "\n"; } int main() {     // taking input     ll N = 5, K = 3, X = 3;      resultArray(N, K, X); } 
Java
import java.util.*;  class GFG {     // Function to generate the result array     static void resultArray(long N, long K, long X) {         // Case when the answer does not exist         if (N < K || X + 1 < K) {             System.out.println("-1");             return;         }         // List to store the answer         List<Long> ans = new ArrayList<>();         // Push all the numbers less than K into          // the answer to get MEX = K         for (long i = 0; i < K; i++) {             ans.add(i);         }         if (X == K) {             for (long i = K; i < N; i++) {                 ans.add(K - 1);             }         }         // Else fill the remaining positions with          // the maximum element allowed         else {             for (long i = K; i < N; i++) {                 ans.add(X);             }         }         // Print the result array         for (Long num : ans) {             System.out.print(num + " ");         }         System.out.println();     }      public static void main(String[] args) {         // Example input values         long N = 5, K = 3, X = 3;         resultArray(N, K, X);     } } 
Python3
def GFG(N, K, X):     # Case when the answer does not exist     if N < K or X + 1 < K:         print("-1")         return          # Array to store the result     ans = []          # Push all the numbers less than K into answer to get MEX = K     for i in range(K):         ans.append(i)          if X == K:         for i in range(K, N):             ans.append(K - 1)     else:         # Else fill the remaining positions with the maximum element allowed         for i in range(K, N):             ans.append(X)          # Print the result array     print(' '.join(map(str, ans)))  # input values N, K, X = 5, 3, 3 GFG(N, K, X) 
C#
using System; using System.Collections.Generic;  class GFG {     // Function to generate the result array     static void ResultArray(long N, long K, long X)     {         // Case when the answer does not exist         if (N < K || X + 1 < K)         {             Console.WriteLine("-1");             return;         }         // List to store the answer         List<long> ans = new List<long>();         // Push all the numbers less than K into        // the answer to get MEX = K         for (long i = 0; i < K; i++)         {             ans.Add(i);         }         if (X == K)         {             for (long i = K; i < N; i++)             {                 ans.Add(K - 1);             }         }         // Else fill the remaining positions with         // the maximum element allowed         else         {             for (long i = K; i < N; i++)             {                 ans.Add(X);             }         }         // Print the result array         foreach (var num in ans)         {             Console.Write(num + " ");         }         Console.WriteLine();     }     static void Main()     {         // Example input values         long N = 5, K = 3, X = 3;         ResultArray(N, K, X);     } } 
JavaScript
function GFG(N, K, X) {     // Case when the answer does not exist     if (N < K || X + 1 < K) {         console.log("-1");         return;     }     // Array to store the result     const ans = [];     // Push all the numbers less than K into answer to get MEX = K     for (let i = 0; i < K; i++) {         ans.push(i);     }     if (X === K) {         for (let i = K; i < N; i++) {             ans.push(K - 1);         }     }     // Else fill the remaining positions with maximum element allowed     else {         for (let i = K; i < N; i++) {             ans.push(X);         }     }     // Print the result array     console.log(ans.join(' ')); } // input values const N = 5, K = 3, X = 3; GFG(N, K, X); 

Output
0 1 2 2 2 

Time Complexity: O(N)
Auxiliary Space: O(N), where N is the size of array.


Next Article
Maximum XOR of Two Numbers in an Array | Set 2

V

vaibhav_gfg
Improve
Article Tags :
  • Competitive Programming
  • DSA
  • Arrays
  • MEX (Minimal Excluded)
Practice Tags :
  • Arrays

Similar Reads

  • Maximizing array sum with given operation
    There is an array consisting of (2 * n - 1) integers. We can change sign of exactly n elements in the array. In other words, we can select exactly n array elements, and multiply each of them by -1. Find the maximum sum of the array. Examples : Input : arr[] = 50 50 50 Output : 150 There is no need t
    6 min read
  • Collect maximum points in an array with k moves
    Given an array of integer and two values k and i where k is the number of moves and i is the index in the array. The task is to collect maximum points in the array by moving either in single or both directions from given index i and making k moves. Note that every array element visited is considered
    9 min read
  • Maximum XOR of Two Numbers in an Array | Set 2
    Given an array arr[] consisting of N integers, the task is to find the maximum Bitwise XOR from all the possible pairs in the given array. Examples: Input: arr[] = {25, 10, 2, 8, 5, 3}Output: 28Explanation:The maximum result is 5^25 = 28. Input: arr[] = {1, 2, 3, 4, 5, 6, 7}Output: 7Explanation:The
    12 min read
  • Maximum sum combination from the given array
    Given an array arr[] of N integers and three integers X, Y and Z. The task is to find the maximum value of (arr[i] * X) + (arr[j] * Y) + (arr[k] * Z) where 0 ? i ? j ? k ? N - 1. Examples: Input: arr[] = {1, 5, -3, 4, -2}, X = 2, Y = 1, Z = -1 Output: 18 (2 * 5) + (1 * 5) + (-1 * -3) = 18 is the max
    12 min read
  • Length of longest sub-array with maximum arithmetic mean.
    Given an array of n-elements find the longest sub-array with the greatest arithmetic mean. The length of the sub-array must be greater than 1 and the mean should be calculated as an integer only.Examples: Input : arr[] = {3, 2, 1, 2} Output : 2 sub-array 3, 2 has greatest arithmetic mean Input :arr[
    5 min read
  • Maximize the sum of modulus with every Array element
    Given an array A[] consisting of N positive integers, the task is to find the maximum possible value of: F(M) = M % A[0] + M % A[1] + .... + M % A[N -1] where M can be any integer value Examples: Input: arr[] = {3, 4, 6} Output: 10 Explanation: The maximum sum occurs for M = 11. (11 % 3) + (11 % 4)
    4 min read
  • Find row with maximum sum in a Matrix
    Given an N*N matrix. The task is to find the index of a row with the maximum sum. That is the row whose sum of elements is maximum. Examples: Input : mat[][] = { { 1, 2, 3, 4, 5 }, { 5, 3, 1, 4, 2 }, { 5, 6, 7, 8, 9 }, { 0, 6, 3, 4, 12 }, { 9, 7, 12, 4, 3 }, }; Output : Row 3 has max sum 35 Input :
    11 min read
  • Longest Sub-array with maximum average value
    Given an array arr[] of n integers. The task is to find the maximum length of the sub-array which has the maximum average value (average of the elements of the sub-array). [Tex] [/Tex]Examples: Input: arr[] = {2, 3, 4, 5, 6} Output: 1 {6} is the required sub-arrayInput: arr[] = {6, 1, 6, 6, 0} Outpu
    6 min read
  • Maximum of minimums of every window size in a given array
    Given an integer array arr[] of size n, the task is to find the maximum of the minimums for every window size in the given array, where the window size ranges from 1 to n. Example: Input: arr[] = [10, 20, 30]Output: [30, 20, 10]Explanation: First element in output indicates maximum of minimums of al
    14 min read
  • Maximum sum with limited queries
    Given an array arr[] of n integers in sorted order, find the maximum number of largest elements that can be selected from the array such that the sum is less than or equal to k. You can select an element any number of times. The sum of the selected elements should be maximized. You can query the val
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences