DDSA Solutions

2054. Two Best Non-Overlapping Events

Time: O(n log n)
Space: O(n)
Advertisement

Approach

Sort events by end time; sweep with prefix max value; binary search for non-overlapping pair.

Key Techniques

Array

Array problems involve manipulating elements stored in a contiguous block of memory. Key techniques include two-pointer traversal, prefix sums, sliding windows, and in-place partitioning. In C#, arrays are zero-indexed and fixed in size — use List<T> when you need dynamic resizing.

Binary Search

Binary search reduces search space by half each step, giving O(log n) time. Beyond sorted arrays, apply it on the answer space ("binary search on result") when you can define a monotonic predicate — e.g., "can we achieve X with k resources?"

Dynamic Programming

Dynamic programming solves problems by breaking them into overlapping sub-problems and storing results to avoid redundant work. The key steps are: define state, write a recurrence relation, set base cases, and choose top-down (memoization) or bottom-up (tabulation). DP often yields O(n²) → O(n) time improvements over brute force.

2054.cs
C#
// Approach: Sort events by end time; sweep with prefix max value; binary search for non-overlapping pair.
// Time: O(n log n) Space: O(n)

public class Solution
{
    public int MaxTwoEvents(int[][] events)
    {
        int ans = 0;
        int maxValue = 0;
        Event[] evts = new Event[events.Length * 2];

        for (int i = 0; i < events.Length; ++i)
        {
            int start = events[i][0];
            int end = events[i][1];
            int value = events[i][2];
            evts[i * 2] = new Event(start, value, 1);
            evts[i * 2 + 1] = new Event(end + 1, value, 0);
        }

        Array.Sort(evts, (a, b) =>
            a.time == b.time ? a.isStart.CompareTo(b.isStart) : a.time.CompareTo(b.time));

        foreach (Event evt in evts)
        {
            if (evt.isStart == 1)
                ans = Math.Max(ans, evt.value + maxValue);
            else
                maxValue = Math.Max(maxValue, evt.value);
        }

        return ans;
    }
}

public class Event
{
    public int time;
    public int value;
    public int isStart;

    public Event(int time, int value, int isStart)
    {
        this.time = time;
        this.value = value;
        this.isStart = isStart;
    }
}
Advertisement
Was this solution helpful?