-
Notifications
You must be signed in to change notification settings - Fork 0
/
Kth_max.java
84 lines (77 loc) · 1.71 KB
/
Kth_max.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//Anshul Chouhan
//0801IT191012
import java.util.*;
class Kth_max {
static int[] heap;
static int curr_size=1;
static int n;
public static void main(String[] args){
Scanner s=new Scanner(System.in);
n=s.nextInt();
curr_size=1;
build(n);
for(int i=0;i<n;i++){
int val=s.nextInt();
insertKey(val);
}
int k=s.nextInt();
if(k>n){
System.out.println("-1");
return;
}
for(int i=0;i<n-k+1;i++){
Extract_Max();
}
System.out.println(Extract_Max());
s.close();
}
static void swap(int i,int j){
int val=heap[i];
heap[i]=heap[j];
heap[j]=val;
}
static void build(int n){
heap=new int[n+1];
}
static int left(int i){
return 2*i;
}
static int right(int i){
return 2*i+1;
}
static int parent(int i){
return i/2;
}
static void insertKey(int val){
heap[curr_size]=val;
int i=curr_size;
curr_size++;
while(i>1 && heap[parent(i)]<heap[i]){
swap(i,parent(i));
i=parent(i);
}
}
static int Extract_Max(){
if(curr_size==0)return -1;
int ans= heap[0];
heap[0]=heap[curr_size-1];
curr_size--;
swim(0);
return ans;
}
private static void swim(int i) {
int l=left(i);
int r=right(i);
int max=i;
if(l < curr_size && heap[l]>heap[i]){
max=l;
}
if(r<curr_size && heap[r]>heap[max]){
max=r;
}
if(max!=i){
swap(i,max);
swim(max);
}
}
}