Tất cả thử thách
Khó 1 đã giải Tỷ lệ chấp nhận 100.0%

Maximum Project Rewards

Choose nonoverlapping projects to earn the largest total reward.

Bạn sẽ học được gì

  • Sort intervals by end time
  • Find the last compatible project with binary search
  • Choose between taking and skipping a project

Đề bài

Xem bản dịch

Each project is [start_day, end_day, reward]. It occupies every day from start_day through end_day, including both endpoints. You can participate in only one project on a day. Choose a subset with the largest total reward. A project starting on another project’s end day conflicts with it.

Implement project_rewards(projects).

Input

projects: Rows of three integers: start day, end day, and reward.

Output

Return the maximum total reward; the chosen projects need not be returned.

Ràng buộc

1 ≤ projects ≤ 200,000. 1 ≤ start_day ≤ end_day ≤ 1,000,000,000. Rewards are positive integers at most 1,000,000,000.

Ví dụ

Ví dụ 1
Đầu vào:
projects = [
    [1, 2, 4],
    [3, 4, 5],
    [2, 3, 10]
]

Kết quả mong đợi:
expected = 10
Đầu vào:
std::vector<std::vector<long long>> projects = {
    {1, 2, 4},
    {3, 4, 5},
    {2, 3, 10}
};

Kết quả mong đợi:
long long expected = 10;
Đầu vào:
long[][] projects = new long[][] {
    new long[] {1, 2, 4},
    new long[] {3, 4, 5},
    new long[] {2, 3, 10}
};

Kết quả mong đợi:
long expected = 10;

Giải thích

The first two projects earn 9 together. The last earns 10 and conflicts with both, so choose it alone.

Ví dụ 2
Đầu vào:
projects = [
    [1, 2, 4],
    [2, 3, 5]
]

Kết quả mong đợi:
expected = 5
Đầu vào:
std::vector<std::vector<long long>> projects = {
    {1, 2, 4},
    {2, 3, 5}
};

Kết quả mong đợi:
long long expected = 5;
Đầu vào:
long[][] projects = new long[][] {
    new long[] {1, 2, 4},
    new long[] {2, 3, 5}
};

Kết quả mong đợi:
long expected = 5;

Giải thích

Both occupy day 2. Choose only the second, with reward 5.

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

This is a weighted interval scheduling problem with overlapping time ranges.

Gợi ý 2

Sort projects by end day and combine each project with the latest compatible earlier one.

Gợi ý 3

Be precise about conflicts: another project starting on an end day still overlaps.

Độ phức tạp mong đợi

O(n log n) time, O(n) extra space

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

# Người giải Ngôn ngữ Thời gian Bộ nhớ AI đánh giá Lời giải
1 ННикита Python 800 ms - 5/5 Xem code

Học hỏi từ người khác

Giải pháp cộng đồng

Cảnh báo: Có 1 lời giải đầy đủ bên dưới Hãy thử tự giải trước. Bạn vẫn có thể xem mã của người khác và đánh giá AI. Đăng nhập và giải thử thách để tham gia thảo luận.