leetcode - 1751. Maximum Number of Events That Can Be Attended II

这篇具有很好参考价值的文章主要介绍了leetcode - 1751. Maximum Number of Events That Can Be Attended II。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Description

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. You are also given an integer k which represents the maximum number of events you can attend.

You can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive: that is, you cannot attend two events where one of them starts and the other ends on the same day.

Return the maximum sum of values that you can receive by attending events.

Example 1:

leetcode - 1751. Maximum Number of Events That Can Be Attended II,OJ题目记录,leetcode,算法,职场和发展

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.

Example 2:

leetcode - 1751. Maximum Number of Events That Can Be Attended II,OJ题目记录,leetcode,算法,职场和发展

Input: events = [[1,2,4],[3,4,3],[2,3,10]], k = 2
Output: 10
Explanation: Choose event 2 for a total value of 10.
Notice that you cannot attend any other event as they overlap, and that you do not have to attend k events.

Example 3:

leetcode - 1751. Maximum Number of Events That Can Be Attended II,OJ题目记录,leetcode,算法,职场和发展

Input: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3
Output: 9
Explanation: Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.

Constraints:

1 <= k <= events.length
1 <= k * events.length <= 10^6
1 <= startDayi <= endDayi <= 10^9
1 <= valuei <= 10^6

Solution

Solved after learning from other solutions…

Recursive, for each interval, either choose it or not. For helper function, we pass index as the current chosen index.

Time complexity: o ( n 2 ) o(n^2) o(n2)
Space complxity: o ( n ) o(n) o(n)

Code

class Solution:
    def __init__(self,) -> None:
        self.memo = {}

    def maxValue(self, events: List[List[int]], k: int) -> int:
        
        def helper(event_index: int, k: int) -> int:
            """
            event_index:
            k:
            """
            if event_index >= len(events) or k == 0:
                return 0
            if (event_index, k) in self.memo:
                return self.memo[(event_index, k)]
            i = event_index + 1
            while i < len(events):
                if events[i][0] > events[event_index][1]:
                    break
                i += 1                
            self.memo[(event_index, k)] = max(helper(i, k - 1) + events[event_index][2], helper(event_index + 1, k))
            return self.memo[(event_index, k)]
        
        events.sort()
        return helper(0, k)

Since events is sorted, we could also use binary search.

class Solution:
    def maxValue(self, events: List[List[int]], k: int) -> int:
        events.sort()
        memo = {}
        def helper(index: int, k: int) -> int:
            if index >= len(events) or k == 0:
                return 0
            if (index, k) in memo:
                return memo[(index, k)]
            # find next appropriate index
            left, right = index + 1, len(events) - 1
            while left < right:
                mid = (left + right) >> 1
                if events[mid][0] <= events[index][1]:
                    left = mid + 1
                else:
                    right = mid
            mid = (left + right) >> 1
            if events[mid][0] <= events[index][1]:
                mid += 1
            # keep answer at memo
            ans = max(events[index][2] + helper(mid, k - 1), helper(index + 1, k))
            memo[(index, k)] = ans
            return memo[(index, k)]
        return helper(0, k)

or using bisect package:文章来源地址https://www.toymoban.com/news/detail-593184.html

class Solution:
    def maxValue(self, events: List[List[int]], k: int) -> int:
        def helper(index: int, k: int) -> int:
            if k == 0 or index >= len(events):
                return 0
            if (index, k) in memo:
                return memo[(index, k)]
            # looking for next possible index
            i = bisect.bisect_right(events_start, events[index][1])
            res = max(events[index][2] + helper(i, k - 1), helper(index + 1, k))
            memo[(index, k)] = res
            return memo[(index, k)]
        events.sort()
        memo = {}
        events_start = [item[0] for item in events]
        return helper(0, k)

到了这里,关于leetcode - 1751. Maximum Number of Events That Can Be Attended II的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • LeetCode每日一题——2520. Count the Digits That Divide a Number

    2520. Count the Digits That Divide a Number Given an integer num, return the number of digits in num that divide num. An integer val divides nums if nums % val == 0. Example 1: Input: num = 7 Output: 1 Explanation: 7 divides itself, hence the answer is 1. Example 2: Input: num = 121 Output: 2 Explanation: 121 is divisible by 1, but not 2. Since 1 occurs twic

    2024年02月08日
    浏览(45)
  • MobaXterm 连接服务器超过指定连接数量(默认14个)Warning: you have reached the maximum number of saved sessions for the

    错误提示: Warning: you have reached the maximum number of saved sessions for the personal edition of MobaXterm. You can start a new session but it wil not be automatically saved. Please support MobaXterm by subscribing to the Professional edition here: https://mobaxterm.mobatek.net 意思就是:警告:您已达到个人版MobaXterm的最大保存会话

    2024年02月14日
    浏览(95)
  • LeetCode646. Maximum Length of Pair Chain——动态规划

    You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti righti. A pair p2 = [c, d] follows a pair p1 = [a, b] if b c. A chain of pairs can be formed in this fashion. Return the length longest chain which can be formed. You do not need to use up all the given intervals. You can select pairs in any order. Example 1: Input: pairs = [[

    2024年02月22日
    浏览(45)
  • leetcode - 2616. Minimize the Maximum Difference of Pairs

    You are given a 0-indexed integer array nums and an integer p. Find p pairs of indices of nums such that the maximum difference amongst all the pairs is minimized. Also, ensure no index appears more than once amongst the p pairs. Note that for a pair of elements at the index i and j, the difference of this pair is |nums[i] - nums[j]|, where |x| represents th

    2024年02月13日
    浏览(40)
  • LeetCode447. Number of Boomerangs

    You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters). Return the number of boomerangs. Example 1: Input: points = [[0,0],[1,0],[2,0]] Output: 2 Explanation: The two boomerangs

    2024年02月02日
    浏览(33)
  • LeetCode 933. Number of Recent Calls

    ou have a  RecentCounter  class which counts the number of recent requests within a certain time frame. Implement the  RecentCounter  class: RecentCounter()  Initializes the counter with zero recent requests. int ping(int t)  Adds a new request at time  t , where  t  represents some time in milliseconds, and returns the number of requests that has h

    2024年02月08日
    浏览(46)
  • LeetCode //C - 2130. Maximum Twin Sum of a Linked List

    In a linked list of size n, where n is even, the i t h i^{th} i t h node (0-indexed) of the linked list is known as the twin of the ( n − 1 − i ) t h (n-1-i)^{th} ( n − 1 − i ) t h node, if 0 = i = (n / 2) - 1. For example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These are the only nodes with twins for n = 4. Th

    2024年01月17日
    浏览(60)
  • LeetCode //C - 1161. Maximum Level Sum of a Binary Tree

    Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on. Return the smallest level x such that the sum of all the values of nodes at level x is maximal.   Example 1: Input: root = [1,7,0,7,-8,null,null] Output: 2 **Explanation: ** Level 1 sum = 1. Level 2 sum = 7 + 0 = 7. Level 3 sum = 7 + -8 = -1. So we return

    2024年01月23日
    浏览(50)
  • LeetCode //C - 933. Number of Recent Calls

    You have a RecentCounter class which counts the number of recent requests within a certain time frame. Implement the RecentCounter class: RecentCounter() Initializes the counter with zero recent requests. int ping(int t) Adds a new request at time t, where t represents some time in milliseconds, and returns the number of requests that has happened in the pas

    2024年01月23日
    浏览(47)
  • A component required a bean of type ‘...Mapper‘ that could not be found问题解决

    错误如图 第一步 查看配置文件是否正确 第二步 查看标签是否正确 检查UserMapper上是否加上@Mapper 补充 第二步还是不行的话查看下POM文件是否导入mybatis-plus-boot-starter 配置mybatis-plus.mapper-locations无提示信息; 此时发现右上角出现感叹号,Cannot resolve configuration property ‘mybatis-

    2024年02月16日
    浏览(39)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包