# Maximum length of rod for Q-th person

Given lengths of n rods in an array a[]. If any person picks any rod, half of the longest rod (or (max + 1) / 2 ) is assigned and remaining part (max – 1) / 2 is put back. It may be assumed that sufficient number of rods are always available, answer M queries given in an array q[] to find the largest length of rod available for qith person, provided qi is a valid person number starting from 1.

Examples :

Input : a[] = {6, 5, 9, 10, 12}
q[] = {1, 3}
Output : 12 9
The first person gets maximum length as 12.
We remove 12 from array and put back (12 -1) / 2 = 5.
Second person gets maximum length as 10.
We put back (10 - 1)/2 which is 4.
Third person gets maximum length as 9.

Input : a[] = {6, 5, 9, 10, 12}
q[] = {3, 1, 2, 7, 4, 8, 9, 5, 10, 6}
Output : 9 12 10 5 6 4 3 6 3 5

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach :
Use a stack and a queue. First sort all the lengths and push them onto a stack. Now, take the top element of stack, and divide by 2 and push the remaining length to queue. Now, from next customer onwards :

1. If stack is empty, pop front queue and push back to queue. It’s half (front / 2), if non zero.
2. If queue is empty, pop from stack and push to queue it’s half (top / 2), if non zero.
3. If both are non empty, compare top and front, which ever is larger should be popped, divided by 2 and then pushed back.
4. If both are empty, store is empty! Stop here!

At each step above store the length available to ith customer in separate array, say “ans”. Now, start answering the queries by giving ans[Qi] as output.

Below is the implementation of above approach :

## C++

 // CPP code to find the length of largest // rod available for Q-th customer #include using namespace std;    // function to find largest length of // rod available for Q-th customer vector maxRodLength(int ar[],                         int n, int m) {     queue q;        // sort the rods according to lengths     sort(ar, ar + n);        // Push sorted elements to a stack     stack s;     for (int i = 0; i < n; i++)         s.push(ar[i]);        vector ans;        while (!s.empty() || !q.empty()) {         int val;                    // If queue is empty -> pop from stack         // and push to queue it’s half(top/2),         // if non zero.         if (q.empty()) {             val = s.top();             ans.push_back(val);             s.pop();             val /= 2;                if (val)                 q.push(val);         }         // If stack is empty -> pop front from         // queue and push back to queue it’s         // half(front/2), if non zero.         else if (s.empty()) {             val = q.front();             ans.push_back(val);             q.pop();             val /= 2;             if (val != 0)                 q.push(val);         }         // If both are non empty ->         // compare top and front, whichsoever is         // larger should be popped, divided by 2         // and then pushed back.         else {             val = s.top();             int fr = q.front();             if (fr > val) {                 ans.push_back(fr);                 q.pop();                 fr /= 2;                 if (fr)                     q.push(fr);             }             else {                 ans.push_back(val);                 s.pop();                 val /= 2;                 if (val)                     q.push(val);             }         }     }        return ans; }    // Driver code int main() {     // n : number of rods     // m : number of queries     int n = 5, m = 10;            int ar[n] = { 6, 5, 9, 10, 12 };        vector ans = maxRodLength(ar, n, m);        int query[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };     int size = sizeof(query) / sizeof(query[0]);     for (int i = 0; i < size; i++)         cout << ans[query[i] - 1] << " ";        return 0; }

## Java

 // JAVA code to find the length of largest // rod available for Q-th customer import java.util.*;    class GFG {    // function to find largest length of // rod available for Q-th customer static Vector maxRodLength(int ar[],                         int n, int m) {     Queue q = new LinkedList<>();        // sort the rods according to lengths     Arrays.sort(ar);        // Push sorted elements to a stack     Stack s = new Stack();     for (int i = 0; i < n; i++)         s.add(ar[i]);        Vector ans = new Vector();        while (!s.isEmpty() || !q.isEmpty())     {         int val;                    // If queue is empty.pop from stack         // and push to queue its half(top/2),         // if non zero.         if (q.isEmpty())         {             val = s.peek();             ans.add(val);             s.pop();             val /= 2;                if (val > 0)                 q.add(val);         }                    // If stack is empty.pop front from         // queue and push back to queue its         // half(front/2), if non zero.         else if (s.isEmpty())         {             val = q.peek();             ans.add(val);             q.remove();             val /= 2;             if (val != 0)                 q.add(val);         }                    // If both are non empty .         // compare top and front, whichsoever is         // larger should be popped, divided by 2         // and then pushed back.         else         {             val = s.peek();             int fr = q.peek();             if (fr > val)             {                 ans.add(fr);                 q.remove();                 fr /= 2;                 if (fr > 0)                     q.add(fr);             }             else              {                 ans.add(val);                 s.pop();                 val /= 2;                 if (val > 0)                     q.add(val);             }         }     }     return ans; }    // Driver code public static void main(String[] args) {     // n : number of rods     // m : number of queries     int n = 5, m = 10;            int []ar = { 6, 5, 9, 10, 12 };        Vector ans = maxRodLength(ar, n, m);        int query[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };     int size = query.length;     for (int i = 0; i < size; i++)         System.out.print(ans.get(query[i] - 1) + " "); } }    // This code is contributed by Rajput-Ji

Output:

12 10 9 6 6 5 5 4 3 3

Time complexity : O(N log(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.

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.

Improved By : Rajput-Ji

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.