-
Notifications
You must be signed in to change notification settings - Fork 0
/
No_2462.cs
46 lines (43 loc) · 1.5 KB
/
No_2462.cs
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
using System.Runtime.InteropServices.Marshalling;
using System.Security.Cryptography.X509Certificates;
namespace LeetCode
{
class No_2462
{
public long TotalCost(int[] costs, int k, int candidates)
{
var frontheap = new PriorityQueue<int, int>();
var backHeap = new PriorityQueue<int, int>();
int i = 0, e = costs.Length - 1, n = Math.Min(candidates, costs.Length);
long output = 0;
for (int j = 0; j < n; j++)
{
if (n <= e)
backHeap.Enqueue(e, costs[e--]);
frontheap.Enqueue(i, costs[i++]);
}
for (int l = 0; l < k; l++)
{
if (frontheap.Count != 0 && backHeap.Count != 0)
{
if (costs[frontheap.Peek()] <= costs[backHeap.Peek()])
{
output += costs[frontheap.Dequeue()];
if (i <= e)
frontheap.Enqueue(i, costs[i++]);
}
else
{
output += costs[backHeap.Dequeue()];
if (e >= i)
backHeap.Enqueue(e, costs[e--]);
}
}
else if (frontheap.Count != 0)
output += costs[frontheap.Dequeue()];
else output += costs[backHeap.Dequeue()];
}
return output;
}
}
}