| | | 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.TwoBestNonOverlappingEvents; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class TwoBestNonOverlappingEventsBinarySearch : 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[1] - b[1]); |
| | | 26 | | |
| | 3 | 27 | | var maxSum = 0; |
| | 3 | 28 | | var maxValueBefore = new int[events.Length]; |
| | 3 | 29 | | var maxValueSoFar = 0; |
| | | 30 | | |
| | 24 | 31 | | for (var i = 0; i < events.Length; i++) |
| | 9 | 32 | | { |
| | 9 | 33 | | var startTime = events[i][0]; |
| | 9 | 34 | | var value = events[i][2]; |
| | | 35 | | |
| | 9 | 36 | | var low = 0; |
| | 9 | 37 | | var high = i - 1; |
| | 9 | 38 | | var maxPreviousValue = 0; |
| | | 39 | | |
| | 17 | 40 | | while (low <= high) |
| | 8 | 41 | | { |
| | 8 | 42 | | var mid = (low + high) / 2; |
| | | 43 | | |
| | 8 | 44 | | if (events[mid][1] < startTime) |
| | 4 | 45 | | { |
| | 4 | 46 | | maxPreviousValue = Math.Max(maxPreviousValue, maxValueBefore[mid]); |
| | | 47 | | |
| | 4 | 48 | | low = mid + 1; |
| | 4 | 49 | | } |
| | | 50 | | else |
| | 4 | 51 | | { |
| | 4 | 52 | | high = mid - 1; |
| | 4 | 53 | | } |
| | 8 | 54 | | } |
| | | 55 | | |
| | 9 | 56 | | maxSum = Math.Max(maxSum, maxPreviousValue + value); |
| | | 57 | | |
| | 9 | 58 | | maxValueSoFar = Math.Max(maxValueSoFar, value); |
| | | 59 | | |
| | 9 | 60 | | maxValueBefore[i] = maxValueSoFar; |
| | 9 | 61 | | } |
| | | 62 | | |
| | 3 | 63 | | return maxSum; |
| | 3 | 64 | | } |
| | | 65 | | } |