HardArraysNot started

Calculate loading bays needed

Each delivery occupies one loading bay from its arrival minute up to, but not including, its departure minute. Read all delivery intervals and print the minimum number of bays needed so no delivery waits. When one delivery departs at the exact minute another arrives, they may use the same bay.

Input

First line N. Next N lines contain arrival and departure minutes, with arrival smaller than departure.

Output

One integer: the maximum number of deliveries present at the same time.

Example 1

Input

5
10 30
20 40
30 50
35 45
60 80

Output

3

Between minutes 35 and 40, three deliveries occupy bays at once.

Constraints

  • 1 <= N <= 100000
  • 0 <= arrival < departure <= 1000000

Hints

Hint 1 of 3

Sort all arrival times and all departure times separately.

Hint 2 of 3

Use two pointers to process whichever event happens next.

Hint 3 of 3

At an equal time, process the departure first because its bay is immediately reusable.

Solution

Show a reference solution and explanation
 Python · reference solution
count = int(input())
intervals = [tuple(map(int, input().split())) for _ in range(count)]
arrivals = sorted(start for start, _ in intervals)
departures = sorted(end for _, end in intervals)
i = j = occupied = needed = 0
while i < count:
    if arrivals[i] < departures[j]:
        occupied += 1
        needed = max(needed, occupied)
        i += 1
    else:
        occupied -= 1
        j += 1
print(needed)

Approach

The two sorted lists form a chronological event stream without building event objects. An arrival increases the occupied count; a departure decreases it. Choosing departure on a tie models half-open intervals, and the highest occupied count is exactly the required number of bays.

Your program
count = int(input())
intervals = [tuple(map(int, input().split())) for _ in range(count)]
# calculate the maximum overlap

Tests: 4 cases including the examples. Available in Python, JavaScript.

How this page was checked. Every reference solution, in every language listed, was run against every test case by the publishing checks. Languages marked “no run” have no in-browser runtime here yet; download your file and run it locally.