Ctrl K

Segments Peaking Within a Range

Medium
You are given an array of non-negative integers values and two numbers low ≤ high. Count the non-empty segments (contiguous pieces of the array) whose largest element lies between low and high, inclusive. Segments with different bounds count separately. The answer is guaranteed to fit in a signed 32-bit integer.
Example 1
values=[1, 6, 2, 9, 3], low=3, high=7 → 5

The valid segments are [1, 6], [1, 6, 2], [6], [6, 2] (maximum 6) and [3] (maximum 3). Anything containing 9 is too high, and [1] or [2] alone peak below 3.

Example 2
values=[4, 4, 4], low=4, high=4 → 6

Every segment has maximum 4, so all six of them count.

Example 3
values=[0, 10, 0], low=1, high=5 → 0
Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • 0 ≤ values[i] ≤ 10⁹
  • 0 ≤ low ≤ high ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTwo Boards Holding Water MediumZero-Sum Triples MediumTriple Sum Nearest the Target MediumFour Numbers to a Target MediumNext Arrangement in Order Medium
loading Python…
Input
values=[1, 6, 2, 9, 3], low=3, high=7
Expected
5

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