Maximum Number of Events That Can Be Attended II — LeetCode 1751 Python Solution

HardArrayBinary SearchDynamic ProgrammingSorting
Problem
#1751
Reading time
3 min

The problem

You are given an array of events where events[i] = [startDayi, endDayi, valuei]. The ith event starts at startDayi and ends at endDayi, and if you attend this event, you will receive a value of valuei.

Example

Input
events = [[1,2,4],[3,4,3],[2,3,1]], k = 2
Output
7
Explanation
Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7.

Python solution

Python
class Solution:
    def maxValue(self, events: List[List[int]], k: int) -> int:
        @cache
        def dfs(i: int, k: int) -> int:
            if i >= len(events):
                return 0
            _, ed, val = events[i]
            ans = dfs(i + 1, k)
            if k:
                j = bisect_right(events, ed, lo=i + 1, key=lambda x: x[0])
                ans = max(ans, dfs(j, k - 1) + val)
            return ans

        events.sort()
        return dfs(0, k)

Complexity

MeasureComplexity
TimeO(n \times \log n + n \times k)
SpaceO(n \times k), where n is the number of events auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 1751. Maximum Number of Events That Can Be Attended II is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1751. Maximum Number of Events That Can Be Attended II?
LeetCode 1751. Maximum Number of Events That Can Be Attended II is rated Hard on LeetCode.
What is the time complexity of LeetCode 1751. Maximum Number of Events That Can Be Attended II?
The Python solution on this page runs in O(n \times \log n + n \times k).
What is the space complexity of LeetCode 1751. Maximum Number of Events That Can Be Attended II?
The Python solution on this page uses O(n \times k), where n is the number of events auxiliary space.
What topics does LeetCode 1751. Maximum Number of Events That Can Be Attended II cover?
LeetCode 1751. Maximum Number of Events That Can Be Attended II is tagged Array, Binary Search, Dynamic Programming and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview