-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
54 lines (48 loc) · 1.43 KB
/
Solution.cs
File metadata and controls
54 lines (48 loc) · 1.43 KB
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
public class Solution
{
public long TotalCost(int[] costs, int k, int candidates)
{
PriorityQueue<int, int> leftQueue = new();
PriorityQueue<int, int> rightQueue = new();
int left = 0;
int right = costs.Length - 1;
while (left < right && left < candidates)
{
leftQueue.Enqueue(costs[left], costs[left]);
left++;
rightQueue.Enqueue(costs[right], costs[right]);
right--;
}
if (left == right && left < candidates)
{
leftQueue.Enqueue(costs[left], costs[left]);
left++;
}
long totalCost = 0;
while (k > 0)
{
int valLeft = leftQueue.Count > 0 ? leftQueue.Peek() : int.MaxValue;
int valRight = rightQueue.Count > 0 ? rightQueue.Peek() : int.MaxValue;
if (valLeft <= valRight)
{
totalCost += leftQueue.Dequeue();
if (left <= right)
{
leftQueue.Enqueue(costs[left], costs[left]);
left++;
}
}
else
{
totalCost += rightQueue.Dequeue();
if (right >= left)
{
rightQueue.Enqueue(costs[right], costs[right]);
right--;
}
}
k--;
}
return totalCost;
}
}