| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 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.TwoBestNonOverlappingEvents; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class TwoBestNonOverlappingEventsPriorityQueue : ITwoBestNonOverlappingEvents |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n log n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="events"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int MaxTwoEvents(int[][] events) |
| 3 | 24 | | { |
| 12 | 25 | | Array.Sort(events, (a, b) => a[0] - b[0]); |
| | 26 | |
|
| 3 | 27 | | var completedEventsPriorityQueue = new PriorityQueue<(int EndTime, int Value), int>(); |
| | 28 | |
|
| 3 | 29 | | var maxValueBeforeCurrent = 0; |
| 3 | 30 | | var maxSum = 0; |
| | 31 | |
|
| 27 | 32 | | foreach (var @event in events) |
| 9 | 33 | | { |
| 9 | 34 | | var startTime = @event[0]; |
| 9 | 35 | | var endTime = @event[1]; |
| 9 | 36 | | var value = @event[2]; |
| | 37 | |
|
| 13 | 38 | | while (completedEventsPriorityQueue.Count > 0 && completedEventsPriorityQueue.Peek().EndTime < startTime) |
| 4 | 39 | | { |
| 4 | 40 | | var completedEvent = completedEventsPriorityQueue.Dequeue(); |
| | 41 | |
|
| 4 | 42 | | maxValueBeforeCurrent = Math.Max(maxValueBeforeCurrent, completedEvent.Value); |
| 4 | 43 | | } |
| | 44 | |
|
| 9 | 45 | | maxSum = Math.Max(maxSum, maxValueBeforeCurrent + value); |
| | 46 | |
|
| 9 | 47 | | completedEventsPriorityQueue.Enqueue((endTime, value), endTime); |
| 9 | 48 | | } |
| | 49 | |
|
| 3 | 50 | | return maxSum; |
| 3 | 51 | | } |
| | 52 | | } |