using
System;
using
System.Collections.Generic;
public
class
GFG {
static
int
LastElement(List<
int
> arr)
{
int
n = arr.Count;
var
pq =
new
PriorityQueue<
int
>();
for
(
int
i = 0; i < n; i++) {
pq.Push(arr[i]);
}
while
(pq.Count > 1) {
int
a = pq.Pop();
int
b = pq.Pop();
if
(a != b) {
a -= b;
pq.Push(a);
}
}
if
(pq.Count == 1) {
return
pq.Top();
}
return
0;
}
static
void
Main()
{
List<
int
> arr =
new
List<
int
>{ 2, 4, 5 };
Console.WriteLine(LastElement(arr));
}
}
public
class
PriorityQueue<T>
where
T : IComparable<T> {
private
List<T> heap;
public
PriorityQueue() { heap =
new
List<T>(); }
public
int
Count
{
get
{
return
heap.Count; }
}
public
void
Push(T value)
{
heap.Add(value);
int
currentIndex = heap.Count - 1;
while
(currentIndex > 0) {
int
parentIndex = (currentIndex - 1) / 2;
if
(heap[currentIndex].CompareTo(
heap[parentIndex])
> 0) {
Swap(currentIndex, parentIndex);
currentIndex = parentIndex;
}
else
{
break
;
}
}
}
public
T Pop()
{
if
(Count == 0) {
throw
new
InvalidOperationException(
"Priority queue is empty"
);
}
T root = heap[0];
heap[0] = heap[Count - 1];
heap.RemoveAt(Count - 1);
int
currentIndex = 0;
while
(
true
) {
int
leftChildIndex = currentIndex * 2 + 1;
int
rightChildIndex = currentIndex * 2 + 2;
if
(leftChildIndex >= Count) {
break
;
}
int
childIndex = leftChildIndex;
if
(rightChildIndex < Count
&& heap[rightChildIndex].CompareTo(
heap[leftChildIndex])
> 0) {
childIndex = rightChildIndex;
}
if
(heap[currentIndex].CompareTo(
heap[childIndex])
< 0) {
Swap(currentIndex, childIndex);
currentIndex = childIndex;
}
else
{
break
;
}
}
return
root;
}
public
T Top()
{
if
(Count == 0) {
throw
new
InvalidOperationException(
"Priority queue is empty"
);
}
return
heap[0];
}
private
void
Swap(
int
index1,
int
index2)
{
T temp = heap[index1];
heap[index1] = heap[index2];
heap[index2] = temp;
}
}