0

An array is given (indexing starts with 1) of size S and N number of queries is given by user N(i)= (M P R); 1<=i<=N. Print the Rth minimum element from the array after updating Mth index. Example: – Array: [2, 4, 6, 1, 7], S=5

Queries: N=3

2 5 3

5 3 2

4 8 4

Output: – 5 2 6

2 Answers2

0
import java.util.*;
import java.io.*;
public class Solution{
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        int S=sc.nextInt();
        int[] arr=new int[S];
        for(int i=0;i<S;i++)
        arr[i]=sc.nextInt();
        int Q=sc.nextInt();
        while(Q>0)
        {
            int M=sc.nextInt();
            int P=sc.nextInt();
            int R=sc.nextInt();
            int[] temp=arr;
            temp[M-1]=P;
            PriorityQueue<Integer> pq=new PriorityQueue<>(Collections.reverseOrder());
            for(int i=0;i<S;i++)
            {
                pq.add(temp[i]);
                if(pq.size()>R)
                pq.poll();
            }
            System.out.println(pq.peek());
            Q--;
        }
    }
}
0

You can answer each query in O(logn) time. The Idea is to use a merge sort tree. This data structure allows O(logn) per update and O(log2n) per query. You can even achieve O(logn) per query and update using gcc's policy based data structures.

harshraj22
  • 130
  • 1
  • 10