-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
47 lines (45 loc) · 1.33 KB
/
Solution.cs
File metadata and controls
47 lines (45 loc) · 1.33 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
public class Solution
{
public long MinimumDifference(int[] nums)
{
int n = nums.Length / 3;
long ans = long.MaxValue;
PriorityQueue<int, int> pqLeft = new();
PriorityQueue<int, int> pqRight = new();
long[] minSumLeft = new long[3 * n];
Array.Fill(minSumLeft, long.MaxValue / 3);
long[] maxSumRight = new long[3 * n];
Array.Fill(maxSumRight, long.MinValue / 3);
long sum = 0;
for (int i = 0; i < n; i++)
{
pqLeft.Enqueue(nums[i], -nums[i]);
sum += nums[i];
minSumLeft[i] = sum;
}
for (int i = n; i < 2 * n; i++)
{
pqLeft.Enqueue(nums[i], -nums[i]);
sum += nums[i] - pqLeft.Dequeue();
minSumLeft[i] = sum;
}
sum = 0;
for (int i = 3 * n - 1; i >= 2 * n; i--)
{
pqRight.Enqueue(nums[i], nums[i]);
sum += nums[i];
maxSumRight[i] = sum;
}
for (int i = 2 * n - 1; i >= n; i--)
{
pqRight.Enqueue(nums[i], nums[i]);
sum += nums[i] - pqRight.Dequeue();
maxSumRight[i] = sum;
}
for (int i = n - 1; i < 2 * n; i++)
{
ans = Math.Min(ans, minSumLeft[i] - maxSumRight[i + 1]);
}
return ans;
}
}