Painting the Fence
InterviewTime limit1sMemory limit128 MB
Bessie walks along a number line and each segment she covers gains a coat of paint; find the total length covered by at least K coats.
- Level
Medium6 of 10
- Topics
- Intervals, Sorting, Prefix sum, Array
- Solved
- No attempts yet
Problem
Farmer John has devised a brilliant method to paint the long fence next to his barn (think of the fence as a one-dimensional number line). He attaches a paint brush to his favorite cow Bessie, then relaxes with a cold glass of water while Bessie walks back and forth across the fence, painting one coat over every segment she passes.
Bessie starts at position and performs a sequence of moves (). For example, the move "10 L" means Bessie moves units to the left, and "15 R" means she moves units to the right. Every segment she walks over receives one coat of paint. During her walk Bessie moves at most units away from the origin.
Given all of Bessie's moves, find the total length (area) of the fence that is painted with at least coats.
Input
- Line 1: Two space-separated integers and .
- Lines 2 to : Each line describes one of Bessie's moves (for example, "15 L"): a distance followed by a direction character,
L(left) orR(right).
Output
- Line 1: The total length of the fence painted with at least coats.
Hint
Suppose , , and Bessie moves right, left, right, left, right, then right. The area painted with at least coats is , consisting of the intervals [-11, -8], [-4, -3], and [0, 2].