Bronze
Batch
Editorial available
Pasture Parcels
/pasture-parcels
Version
v1
Published
Apr 23, 2026, 10:56 PM
Updated
Apr 23, 2026, 10:56 PM
Testsets
1
Statement
Rendered as plain statement text from the published version.
# Pasture Parcels
## Problem
Farmer John has a long fence along his pasture, and different sections of it have been grazed by his cows. Each grazed section is represented as a closed interval `[l, r]` on the fence.
Your task is to determine the total length of fence that has been grazed. When multiple grazed sections overlap or touch, they merge into a single contiguous section.
## Input
The first line contains an integer `N` (1 ≤ N ≤ 10^5), the number of grazed intervals.
The next `N` lines each contain two integers `l` and `r` (−2^31 ≤ l ≤ r ≤ 2^31 − 1), representing a closed interval `[l, r]` of grazed fence.
## Output
Output a single integer: the total length of fence that has been grazed, calculated as the sum of the lengths of all merged intervals. For an interval `[l, r]`, the length is `r - l`.
## Constraints
- 1 ≤ N ≤ 10^5
- −2^31 ≤ l ≤ r ≤ 2^31 − 1
- Coordinates fit in 32-bit signed integers
## Sample Input
```
4
1 4
3 7
10 12
11 15
```
## Sample Output
```
11
```
## Explanation
The intervals `[1, 4]` and `[3, 7]` overlap and merge into `[1, 7]` with length 7 − 1 = 6.
The intervals `[10, 12]` and `[11, 15]` overlap and merge into `[10, 15]` with length 15 − 10 = 5.
The total grazed length is 6 + 5 = 11.