using
System;
using
System.Collections.Generic;
class
GFG {
static
int
CalculateMaxVal(List<
int
> nums,
int
N)
{
PriorityQueue<
int
> decreasing
=
new
PriorityQueue<
int
>(
new
Comparison<
int
>(
(x, y) => y.CompareTo(x)));
int
val = 0;
for
(
int
i = 0; i < N; i++) {
if
(nums[i] == 0) {
if
(decreasing.Count > 0) {
val += decreasing.Dequeue();
}
}
else
{
decreasing.Enqueue(nums[i]);
}
}
return
val;
}
static
void
Main(
string
[] args)
{
int
N = 8;
List<
int
> nums
=
new
List<
int
>() { 5, 1, 2, 0, 0, 4, 3, 0 };
Console.WriteLine(
"Maximum value is: "
+ CalculateMaxVal(nums, N));
}
}
public
class
PriorityQueue<T> {
private
List<T> _heap;
private
Comparison<T> _comparison;
public
PriorityQueue() { _heap =
new
List<T>(); }
public
PriorityQueue(Comparison<T> comparison)
{
_heap =
new
List<T>();
_comparison = comparison;
}
public
void
Enqueue(T item)
{
_heap.Add(item);
int
i = _heap.Count - 1;
while
(i > 0) {
int
j = (i - 1) / 2;
if
(_comparison ==
null
) {
if
(((IComparable<T>)_heap[j])
.CompareTo(item)
<= 0) {
break
;
}
}
else
{
if
(_comparison(_heap[j], item) <= 0) {
break
;
}
}
_heap[i] = _heap[j];
i = j;
}
_heap[i] = item;
}
public
T Dequeue()
{
int
lastIndex = _heap.Count - 1;
T frontItem = _heap[0];
_heap[0] = _heap[lastIndex];
_heap.RemoveAt(lastIndex);
--lastIndex;
int
i = 0;
while
(
true
) {
int
left = i * 2 + 1;
if
(left > lastIndex) {
break
;
}
int
right = left + 1;
if
(right <= lastIndex
&& (_comparison ==
null
? ((IComparable<T>)_heap[left])
.CompareTo(_heap[right])
> 0
: _comparison(_heap[left],
_heap[right])
> 0)) {
left = right;
}
if
(_comparison ==
null
? ((IComparable<T>)_heap[i])
.CompareTo(_heap[left])
<= 0
: _comparison(_heap[i], _heap[left])
<= 0) {
break
;
}
T tmp = _heap[i];
_heap[i] = _heap[left];
_heap[left] = tmp;
i = left;
}
return
frontItem;
}
public
int
Count
{
get
{
return
_heap.Count; }
}
}