Balanced Lineup
InterviewTime limit2sMemory limit256 MB
Given fans sorted by x-coordinate with a gender bit each, find the longest contiguous segment that has an equal number of men and women.
- Level
Medium5 of 10
- Topics
- Prefix sum, Hash map, Sorting, Array
- Solved
- No attempts yet
Problem
Fans stand in one line at distinct x-coordinates. You may choose a group consisting of consecutive people in this line. A group is balanced if it contains the same number of men and women.
The length of a group is the difference between the smallest and largest x-coordinate in that group. Find the maximum length among all balanced groups.
Input
The first line contains the number of fans N (1 ≤ N ≤ 1,000,000).
Each of the next N lines contains a gender value and an x-coordinate, separated by a space. Gender is given as 0 for a man and 1 for a woman. Each x-coordinate is between 0 and 1,000,000,000 inclusive, and no two fans stand at the same x-coordinate. At least one fan of each gender exists.
Output
Print the length of the longest group satisfying the condition.