/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class MaxHeap
{
int capacity;
int size;
int arr[];
MaxHeap(int capacity){
this.capacity = capacity;
size = 0;
this.arr = new int[capacity];
}
int parent(int i) {
return (i - 1) / 2;
}
/*returns the left child of ith Node*/
int left(int i) {
return 2 * i + 1;
}
/*Returns the right child of the ith Node*/
int right(int i) {
return 2 * i + 2;
}
void insert(int ele){
if(size == capacity){
System.
out.
println("Heap overflow"); return;
}
arr[size] = ele;
int k = size;
size++;
while(k!=0&&arr[k]>arr[parent(k)]){
//swap
int temp = arr[parent(k)];
arr[parent(k)] = arr[k];
arr[k] = temp;
k = parent(k);
}
}
int getMax() {
return arr[0];
}
{
// your code goes here
MaxHeap h = new MaxHeap(20);
h.insert(4);
h.insert(1);
h.insert(2);
h.insert(6);
h.insert(7);
h.insert(3);
h.insert(8);
h.insert(5);
System.
out.
println("Max value is " + h.
getMax()); h.insert(99);
System.
out.
println("Max value is " + h.
getMax()); }
}
LyogcGFja2FnZSB3aGF0ZXZlcjsgLy8gZG9uJ3QgcGxhY2UgcGFja2FnZSBuYW1lISAqLwoKaW1wb3J0IGphdmEudXRpbC4qOwppbXBvcnQgamF2YS5sYW5nLio7CmltcG9ydCBqYXZhLmlvLio7CgovKiBOYW1lIG9mIHRoZSBjbGFzcyBoYXMgdG8gYmUgIk1haW4iIG9ubHkgaWYgdGhlIGNsYXNzIGlzIHB1YmxpYy4gKi8KY2xhc3MgTWF4SGVhcAp7CglpbnQgY2FwYWNpdHk7CglpbnQgc2l6ZTsKCWludCBhcnJbXTsKCU1heEhlYXAoaW50IGNhcGFjaXR5KXsKCQl0aGlzLmNhcGFjaXR5ID0gY2FwYWNpdHk7CgkJc2l6ZSA9IDA7CgkJdGhpcy5hcnIgPSBuZXcgaW50W2NhcGFjaXR5XTsKCX0KaW50IHBhcmVudChpbnQgaSkgewogICAgcmV0dXJuIChpIC0gMSkgLyAyOwogIH0K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