You are given an integer array nums
and two integers left
and right
. Return the number of contiguous subarrays where the value of the maximum array element in that subarray is in the range [left, right]
.
nums = [2, 1, 4, 3]
, left = 2
, right = 3
3
[2]
, [2, 1]
, and [3]
.nums
?
nums
are integers.nums
and the bounds left
and right
?
nums
, left
, and right
are all integers, where:
1 <= nums.length <= 10^5
0 <= nums[i] <= 10^9
0 <= left <= right <= 10^9
We’ll utilize a two-pointer approach to solve this problem efficiently:
start
: to track the beginning of the current subarray.count
: to count valid subarrays ending at the current index.[left, right]
, it extends the number of valid subarrays ending at the current index.right
, reset the count of valid subarrays as it breaks the subarray constraint.left
, continue and add previous valid subarrays to the result.The time complexity of this solution is O(n) because we iterate through the array once.
Here is the Python implementation following the above strategy:
def numSubarrayBoundedMax(nums, left, right):
start = 0
count = 0
result = 0
prev_count = 0
for i in range(len(nums)):
if left <= nums[i] <= right:
count = i - start + 1
prev_count = count
elif nums[i] < left:
# This subarray can be part of a valid subarray if previous elements were valid
count = prev_count
else: # nums[i] > right
start = i + 1
count = 0
prev_count = 0
result += count
return result
# Example usage:
nums = [2, 1, 4, 3]
left = 2
right = 3
print(numSubarrayBoundedMax(nums, left, right)) # Output: 3
This solution ensures we efficiently count the valid subarrays by only iterating through the list once and keeping track of the count of valid subarrays incrementally.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?