内容中心

2026年知名的数据中心机房建设品牌公司推荐-浙江宏创晟业信息科技有限公司

To solve the problem of finding the maximum number of non-overlapping intervals (activity selection problem), we can use a greedy algorithm that leverages sorting to optimize the selection process.

Approach

The key insight here is to select the interval that ends the earliest at each step. This leaves the maximum possible time for subsequent intervals, which maximizes the number of non-overlapping intervals we can choose. Here are the detailed steps:

  1. Sort Intervals: First, sort all intervals by their end times in ascending order. This ensures we always consider the interval that finishes earliest next.
  2. Greedy Selection:
    • Start with the first interval (since it ends earliest).
    • For each subsequent interval, check if it starts after the previous selected interval ends. If it does, select it and update the end time of the last selected interval.
  3. Count Selected Intervals: The count of selected intervals gives the maximum number of non-overlapping intervals.

Solution Code

def max_non_overlapping_intervals(intervals):
    if not intervals:
        return 0

    # Sort intervals by their end time
    intervals.sort(key=lambda x: x[1])

    count = 1
    last_end = intervals[0][1]

    for start, end in intervals[1:]:
        if start >= last_end:
            count += 1
            last_end = end

    return count

Explanation

Let’s break down the solution using an example:

  • Input: [[1, 2], [2, 3], [3,4], [1,3]]
  • Sorted by end time: [[1, 2], [2,3], [1,3], [3,4]]
  • Selection:
    • Pick [1, 2] (count=1, last_end=2).
    • Next, [2,3] starts at 2 (>= last_end), so pick it (count=2, last_end=3).
    • Skip [1,3] (starts at 1 < last_end=3).
    • Pick [3,4] (starts at3 >= last_end=3, count=3).
  • Result: 3.

This approach runs in O(n log n) time (due to sorting) and O(1) additional space (excluding input storage), making it efficient for large datasets.

Answer: The function max_non_overlapping_intervals returns the maximum number of non-overlapping intervals. For example, if the input is [[1,2],[2,3],[3,4],[1,3]], the answer is 3.

If you provide the specific input from the image, I can give the exact output, but this solution handles all cases of the interval selection problem. For the purpose of this problem, the code above is the correct solution.

\boxed{3} (assuming the input is the example I used; adjust based on actual input from the image). However, if the input is different, the code will compute the correct result. For example, if the input is [[1,4],[2,3],[3,4]], the answer is \boxed{2}.

Please replace the boxed value with the result from your specific input, but the code is the core solution. \boxed{3}

浙江宏创晟业信息科技有限公司

浙江宏创晟业信息科技有限公司



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?