Skip to content
Problem 795 · LeetCode 795(opens in a new tab)

Number of Subarrays with Bounded Maximum

MediumArrays

You are given an array of whole numbers, nums, and two bounds, left and right.

Count the contiguous, non-empty slices of nums (subarrays) whose largest element lies between left and right, both ends included. The answer fits in a 32-bit integer.

Example 1

Input:  nums = [3, 6, 1, 9, 4], left = 2, right = 6
Output: 6
Why:    [3], [6], [3,6], [6,1], [3,6,1] and [4]
2 more examples and the constraints

Example 2

Input:  nums = [5, 5, 5], left = 5, right = 5
Output: 6
Why:    every one of the 6 subarrays has maximum 5

Example 3

Input:  nums = [1, 0, 1], left = 2, right = 4
Output: 0
Why:    no value reaches 2, so no maximum does

Constraints

  • 1 ≤ length of nums ≤ 100,000
  • 0 ≤ nums[i] ≤ 1,000,000,000
  • 0 ≤ left ≤ right ≤ 1,000,000,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Every start, growing rightO(n²)
  2. Count by right endO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 numbersVerdict
Every start, growing rightO(n²)
Clear; too slow at the limit
Count by right endO(n)
Best; one pass

n = length of nums.

Edge cases to test

  • Nothing reaches left. [1, 0, 1] with bounds 2 to 4 gives 0: inr stays −1.
  • Everything is too big. [9, 8] with bounds 1 to 5 gives 0: big keeps up with inr.
  • All values allowed. [5, 5, 5] with bounds 5 to 5 counts all 6 subarrays.
  • Small values around a fit. [0, 3, 0] with bounds 2 to 4 gives 4: every subarray holding the 3.
  • left equals 0. Every subarray with no value above right counts, including ones of zeros.

Common mistakes

  • Counting only i − big subarrays, which includes ones made only of values below left.
  • Resetting inr when a value below left appears; it must keep the last good index.
  • Not moving inr when a value above right appears, so inr − big turns negative or counts the big value.

How to talk through it

  1. 1Clarify. Are both bounds inclusive? Can values be 0? Does the answer fit in 32 bits?
  2. 2Give the brute force. Grow each start to the right with a running max, stopping above right: O(n²).
  3. 3Count by the right end. Valid starts lie after the last too-big value and no later than the last value of at least left.
  4. 4Code the pass. Track big and inr, add max(0, inr − big) at each index.
  5. 5Test out loud. Run Example 1, all values too small, all too big, and all equal before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?