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.
1using System;
2
3public class Solution {
4 private static int CountSubarrays(int[] nums, int bound) {
5 int count = 0, result = 0, current = 0;
6 foreach (int num in nums) {
7 if (num <= bound) {
8 current++;
9 } else {
10 current = 0;
11 }
12 result += current;
13 }
14 return result;
15 }
16
17 public static int NumSubarrayBoundedMax(int[] nums, int left, int right) {
18 return CountSubarrays(nums, right) - CountSubarrays(nums, left - 1);
19 }
20
21 public static void Main() {
22 int[] nums = {2, 1, 4, 3};
23 int left = 2, right = 3;
24 Console.WriteLine(NumSubarrayBoundedMax(nums, left, right));
25 }
26}
C# implementation maintains the same approach structural logic with a focus on enumerating through the array to assess subarray bounds and employing subtraction to discern required subarrays.
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) {
2
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.