Sponsored
Sponsored
To solve this problem, we iterate through the array and use two helper functions to find the number of subarrays with maximum elements less than or equal to `right` and strictly less than `left`. The result is the difference between these two values.
Time Complexity: O(n), where n is the length of the array because we pass through the array twice both in O(n) time.
Space Complexity: O(1) as we only use a fixed amount of extra space.
1function countSubarrays(nums, bound) {
2 let count = 0, result = 0, current = 0;
3 for (let num of nums) {
4 if (num <= bound) {
5 current++;
6 } else {
7 current = 0;
8 }
9 result += current;
10 }
11 return result;
12}
13
14function numSubarrayBoundedMax(nums, left, right) {
15 return countSubarrays(nums, right) - countSubarrays(nums, left - 1);
16}
17
18const nums = [2, 1, 4, 3];
19const left = 2;
20const right = 3;
21console.log(numSubarrayBoundedMax(nums, left, right));
The JavaScript code adopts an iterative method akin to other languages where subarrays within bounds are identified via numeric comparisons. We rely on differences derived from function call results.
This approach utilizes a sliding window to dynamically check and adjust the range within the array where subarrays satisfy the maximum constraints between `left` and `right`. We scan and adjust pointers to pinpoint valid ranges continuously.
Time Complexity: O(n), scanning and resolving limits in a single pass.
Space Complexity: O(1) maintaining concise storage need.
1function numSubarrayBoundedMax(nums, left, right) {
This JavaScript implementation executes a sliding-window-like mechanics through a loop that assesses alignments of elements within set bounds. This efficiently measures valid subarray formations by extending arrays.