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:
Aggressive Cows
Next article icon

Find the maximum value of the K-th smallest usage value in Array

Last Updated : 22 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size N and with integers M, K. You are allowed to perform an operation where you can increase the value of the least element of the array by 1. You are to do this M times. The task is to find the largest possible value for the Kth smallest value among arr[] after M operations.

Examples

Input: M=10, K=4, arr={5,5,5,5,5}.
Output: 7
Explanation: After 5 operations, each element of the array become 6, and similarly after the next 5 operations, each element of the array become 7.

Input: M=7, K=2, arr={5,9,3,6,4,3};
Output: 5
Explanation: Can use 5 operations to increase the 3 smallest values to 5. Cannot further improve 2-nd smallest with the remaining 2 operations.

Input: M=10,K=4, arr={1,2,3,4,5};
Output: 5
Explanation: Can perform operations to fill all values to 5. The 4-th smallest value is thus 5.

Approach/Intuition:

Binary Search:

One way is to use binary search to find the maximum such answer value that can be achieved by distributing M among K values. If the current mid value is feasible, then the value of the mid is stored as our potential answer, and the search is continued in the upper half of that current search range. Otherwise, the search is continued in the lower half of the search range.

Follow the below steps to implement the above approach:

  • First, initialize the input array and variables M and K, and call to getVal function, to return us the answer.
  • Now, inside the getVal function,
    • sort the array.
    • initialize the search range from 0 to 1e9.
    • for current mid value, check it is valid or not, if it is valid store it as our answer, and change the range to upper half, otherwise if not valid, change the search range to lower half.

Below is the code to implement the above steps:

C++14
// C++ code to implement the above approach. #include <bits/stdc++.h> using namespace std;  //  check function to validate our selected kth largest //  value. bool check(int mid, int M, int K, vector<int>& arr) {     vector<int> temp;     for (int i = 0; i < arr.size(); i++) {         if (arr[i] < mid) {             temp.push_back(arr[i]);         }     }      if (temp.size() < K)         return 1;      for (int i = 0; i < temp.size(); i++) {         if (M + temp[i] < mid)             return 0;         int minVal = min(M, mid - temp[i]);          temp[i] += minVal;         M -= minVal;     }      return 1; }  //  binary search over the range for finding the exact //  answer. int getVal(int& M, int& K, vector<int>& arr) {     sort(arr.begin(), arr.end());     int lo = 0, hi = 1e9;     int ans;     while (lo <= hi) {         int mid = (lo + hi) / 2;          if (check(mid, M, K, arr)) {             ans = mid;             lo = mid + 1;         }         else             hi = mid - 1;     }      return ans; }  // Driver's code int main() {     int M = 10, K = 4;      vector<int> arr = { 1, 2, 3, 4, 5 };      cout << getVal(M, K, arr);     return 0; } 
Java
// C++ code to implement the above approach. import java.util.*;  public class Main {     //  check function to validate our selected kth largest     //  value.     static boolean check(int mid, int M, int K,                          List<Integer> arr)     {         List<Integer> temp = new ArrayList<>();         for (int i = 0; i < arr.size(); i++) {             if (arr.get(i) < mid) {                 temp.add(arr.get(i));             }         }          if (temp.size() < K)             return true;          for (int i = 0; i < temp.size(); i++) {             if (M + temp.get(i) < mid)                 return false;             int minVal = Math.min(M, mid - temp.get(i));              temp.set(i, temp.get(i) + minVal);             M -= minVal;         }          return true;     }      //  binary search over the range for finding the exact     //  answer.     static int getVal(int M, int K, List<Integer> arr)     {         Collections.sort(arr);         int lo = 0, hi = (int)1e9;         int ans = 0;         while (lo <= hi) {             int mid = (lo + hi) / 2;              if (check(mid, M, K, arr)) {                 ans = mid;                 lo = mid + 1;             }             else                 hi = mid - 1;         }          return ans;     }      // Driver's code     public static void main(String[] args)     {         int M = 10, K = 4;          List<Integer> arr             = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));          System.out.println(getVal(M, K, arr));     } } // This code is contributed by chetan bargal(chetanb13) 
Python3
# Python3 code to implement the above approach. from typing import List  # check function to validate our selected kth largest value. def check(mid: int, M: int, K: int, arr: List[int]) -> bool:     temp = []     for i in range(len(arr)):         if arr[i] < mid:             temp.append(arr[i])      if len(temp) < K:         return True      for i in range(len(temp)):         if M + temp[i] < mid:             return False         minVal = min(M, mid - temp[i])          temp[i] += minVal         M -= minVal      return True  # binary search over the range for finding the exact answer. def getVal(M: int, K: int, arr: List[int]) -> int:     arr.sort()     lo = 0     hi = 10**9     ans = 0      while lo <= hi:         mid = (lo + hi) // 2          if check(mid, M, K, arr):             ans = mid             lo = mid + 1         else:             hi = mid - 1      return ans  # Drive code if __name__ == '__main__':     M = 10     K = 4     arr = [1, 2, 3, 4, 5]     print(getVal(M, K, arr))   # This Code is contributed by nikhilsainiofficial546 
C#
using System; using System.Collections.Generic; using System.Linq;  class Program {     // Check function to validate our selected kth largest     // value.     static bool Check(int mid, int M, int K, List<int> arr)     {         List<int> temp = new List<int>();         for (int i = 0; i < arr.Count; i++) {             if (arr[i] < mid) {                 temp.Add(arr[i]);             }         }          if (temp.Count < K)             return true;          for (int i = 0; i < temp.Count; i++) {             if (M + temp[i] < mid)                 return false;             int minVal = Math.Min(M, mid - temp[i]);              temp[i] += minVal;             M -= minVal;         }          return true;     }      // Binary search over the range for finding the exact     // answer.     static int GetVal(ref int M, ref int K, List<int> arr)     {         arr.Sort();         int lo = 0, hi = 1000000000;         int ans = 0;         while (lo <= hi) {             int mid = (lo + hi) / 2;              if (Check(mid, M, K, arr)) {                 ans = mid;                 lo = mid + 1;             }             else                 hi = mid - 1;         }          return ans;     } //Driver code     static void Main(string[] args)     {         int M = 10, K = 4;          List<int> arr = new List<int>() { 1, 2, 3, 4, 5 };          Console.WriteLine(GetVal(ref M, ref K, arr));     } } 
JavaScript
    // Javascript code to implement the above approach.          //  check function to validate our selected kth largest     //  value.     function check(mid, M, K, arr) {     let temp = [];     for (let i = 0; i < arr.length; i++) {         if (arr[i] < mid) {             temp.push(arr[i]);         }     }          if (temp.length < K)         return true;          for (let i = 0; i < temp.length; i++) {         if (M + temp[i] < mid)             return false;         let minVal = Math.min(M, mid - temp[i]);              temp[i] += minVal;         M -= minVal;     }          return true;     }          //  binary search over the range for finding the exact     //  answer.     function getVal(M, K, arr) {     arr.sort((a, b) => a - b);     let lo = 0, hi = 1e9;     let ans;     while (lo <= hi) {         let mid = Math.floor((lo + hi) / 2);              if (check(mid, M, K, arr)) {             ans = mid;             lo = mid + 1;         }         else             hi = mid - 1;     }          return ans;     }          // Driver's code     let M = 10, K = 4;     let arr = [1, 2, 3, 4, 5];          console.log(getVal(M, K, arr));          // This code is contributed by Vaibhav Nandan      

Output
5

Time Complexity: O(NlogN), where N is the size of the 'arr' vector, as it involves iterating through the entire vector once. The time complexity of the 'getVal' function is O(N log N), where N is the size of the 'arr' vector, as it involves sorting the 'arr' vector and performing a binary search on it.
Auxiliary Space: O(N), as it involves storing the 'arr' vector and the 'temp' vector inside the 'check' function.


Next Article
Aggressive Cows
author
prophet1999
Improve
Article Tags :
  • DSA
  • Arrays
  • Binary Search
Practice Tags :
  • Arrays
  • Binary Search

Similar Reads

  • Binary Search on Answer Tutorial with Problems
    Binary Search on Answer is the algorithm in which we are finding our answer with the help of some particular conditions. We have given a search space in which we take an element [mid] and check its validity as our answer, if it satisfies our given condition in the problem then we store its value and
    15+ min read
  • Time Crunch Challenge
    Geeks for Geeks is organizing a hackathon consisting of N sections, each containing K questions. The duration of the hackathon is H hours. Each participant can determine their speed of solving questions, denoted as S (S = questions-per-hour). During each hour, a participant can choose a section and
    11 min read
  • Find minimum subarray length to reduce frequency
    Given an array arr[] of length N and a positive integer k, the task is to find the minimum length of the subarray that needs to be removed from the given array such that the frequency of the remaining elements in the array is less than or equal to k. Examples: Input: n = 4, arr[] = {3, 1, 3, 6}, k =
    10 min read
  • Maximize minimum sweetness in cake cutting
    Given that cake consists of N chunks, whose individual sweetness is represented by the sweetness[] array, the task is to cut the cake into K + 1 pieces to maximize the minimum sweetness. Examples: Input: N = 6, K = 2, sweetness[] = {6, 3, 2, 8, 7, 5}Output: 9Explanation: Divide the cake into [6, 3],
    7 min read
  • Maximize minimum element of an Array using operations
    Given an array A[] of N integers and two integers X and Y (X ≤ Y), the task is to find the maximum possible value of the minimum element in an array A[] of N integers by adding X to one element and subtracting Y from another element any number of times, where X ≤ Y. Examples: Input: N= 3, A[] = {1,
    9 min read
  • Maximize the minimum element and return it
    Given an array A[] of size N along with W, K. We can increase W continuous elements by 1 where we are allowed to perform this operation K times, the task is to maximize the minimum element and return the minimum element after operations. Examples: Input: N = 6, K = 2, W = 3, A[] = {2, 2, 2, 2, 1, 1}
    8 min read
  • Find the maximum value of the K-th smallest usage value in Array
    Given an array arr[] of size N and with integers M, K. You are allowed to perform an operation where you can increase the value of the least element of the array by 1. You are to do this M times. The task is to find the largest possible value for the Kth smallest value among arr[] after M operations
    7 min read
  • Aggressive Cows
    Given an array stalls[] which denotes the position of a stall and an integer k which denotes the number of aggressive cows. The task is to assign stalls to k cows such that the minimum distance between any two of them is the maximum possible. Examples: Input: stalls[] = [1, 2, 4, 8, 9], k = 3Output:
    15+ min read
  • Minimum time to complete at least K tasks when everyone rest after each task
    Given an array arr[] of size n representing the time taken by a person to complete a task. Also, an array restTime[] which denotes the amount of time one person takes to rest after finishing a task. Each person is independent of others i.e. they can work simultaneously on different tasks at the same
    8 min read
  • Maximum count of integers to be chosen from given two stacks having sum at most K
    Given two stacks stack1[] and stack2[] of size N and M respectively and an integer K, The task is to count the maximum number of integers from two stacks having sum less than or equal to K. Examples: Input: stack1[ ] = { 60, 90, 120 }stack2[ ] = { 100, 10, 10, 250 }, K = 130Output: 3Explanation: Tak
    9 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