Ctrl K

Rug Over Painted Stretches

Medium
Floor cells are numbered with integers. The array stretches describes painted areas: a pair [a, b] means every cell from a to b inclusive is painted. The stretches do not overlap and may come in any order. You have one rug rug cells long, which can be laid anywhere as a solid strip of consecutive cells. Return the largest number of painted cells the rug can cover.
Example 1
stretches=[[3, 6], [9, 9], [14, 20]], rug=8 → 7

A rug over cells 13 to 20 covers the whole stretch [14, 20], 7 cells. Placing it over 3 to 10 would give only 4 + 1 = 5.

Example 2
stretches=[[50, 52], [1, 2]], rug=1 → 1

A rug of length 1 covers exactly one cell, so any painted cell will do.

Example 3
stretches=[[1, 4], [6, 7], [9, 12]], rug=7 → 6
Constraints
  • 1 ≤ len(stretches) ≤ 5 · 10⁴
  • 1 ≤ a ≤ b ≤ 10⁹ for every pair [a, b]
  • 1 ≤ rug ≤ 10⁹
  • The stretches do not overlap
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsEven Out With Increments MediumRichest Row of Houses MediumNudge Values to Agree MediumFlowerbed Beauty on a Budget HardMost Items Within Budget Easy
loading Python…
Input
stretches=[[3, 6], [9, 9], [14, 20]], rug=8
Expected
7

Run checks the first 3 tests in your browser. Submit checks all 112 tests on the server, hidden ones included.