| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | | 3 | | // All Rights Reserved. |
| | | 4 | | // -------------------------------------------------------------------------------- |
| | | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | | 9 | | // known as Yevhenii Yeriemeieiv). |
| | | 10 | | // -------------------------------------------------------------------------------- |
| | | 11 | | |
| | | 12 | | namespace LeetCode.Algorithms.ZeroArrayTransformation3; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class ZeroArrayTransformation3PriorityQueue : IZeroArrayTransformation3 |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O((n + q) log q) |
| | | 19 | | /// sPACE complexity - O(n + q) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="nums"></param> |
| | | 22 | | /// <param name="queries"></param> |
| | | 23 | | /// <returns></returns> |
| | | 24 | | public int MaxRemoval(int[] nums, int[][] queries) |
| | 3 | 25 | | { |
| | 9 | 26 | | Array.Sort(queries, (a, b) => a[0] - b[0]); |
| | | 27 | | |
| | 3 | 28 | | var prefixSum = new int[nums.Length + 1]; |
| | | 29 | | |
| | 3 | 30 | | var priorityQueue = new PriorityQueue<int, int>(); |
| | | 31 | | |
| | 3 | 32 | | var count = 0; |
| | | 33 | | |
| | 25 | 34 | | for (int i = 0, j = 0; i < nums.Length; i++) |
| | 9 | 35 | | { |
| | 9 | 36 | | count += prefixSum[i]; |
| | | 37 | | |
| | 17 | 38 | | while (j < queries.Length && queries[j][0] == i) |
| | 8 | 39 | | { |
| | 8 | 40 | | priorityQueue.Enqueue(queries[j][1], -queries[j][1]); |
| | | 41 | | |
| | 8 | 42 | | j++; |
| | 8 | 43 | | } |
| | | 44 | | |
| | 14 | 45 | | while (count < nums[i] && priorityQueue.Count > 0 && priorityQueue.Peek() >= i) |
| | 5 | 46 | | { |
| | 5 | 47 | | count += 1; |
| | | 48 | | |
| | 5 | 49 | | prefixSum[priorityQueue.Dequeue() + 1]--; |
| | 5 | 50 | | } |
| | | 51 | | |
| | 9 | 52 | | if (count < nums[i]) |
| | 1 | 53 | | { |
| | 1 | 54 | | return -1; |
| | | 55 | | } |
| | 8 | 56 | | } |
| | | 57 | | |
| | 2 | 58 | | return priorityQueue.Count; |
| | 3 | 59 | | } |
| | | 60 | | } |