Created
April 26, 2025 19:50
-
-
Save tatsuyax25/3ea0480636c9028ca6658ec2164c7006 to your computer and use it in GitHub Desktop.
You are given an integer array nums and two integers minK and maxK. A fixed-bound subarray of nums is a subarray that satisfies the following conditions: The minimum value in the subarray is equal to minK.
The maximum value in the subarray is equal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[]} nums | |
* @param {number} minK | |
* @param {number} maxK | |
* @return {number} | |
*/ | |
var countSubarrays = function(nums, minK, maxK) { | |
// Initialize variables to keep track of indices and result | |
let minI = -1; // Index of the last occurrence of minK | |
let maxI = -1; // Index of the last occurrence of maxK | |
let ans = 0; // Total count of valid subarrays | |
let leftBoundary = -1; // Left boundary of the current subarray | |
// Iterate through the input array | |
for (let current = 0; current < nums.length; current++) { | |
// Update minI and maxI if the current element matches minK or maxK | |
if (nums[current] === minK) { | |
minI = current; | |
} | |
if (nums[current] === maxK) { | |
maxI = current; | |
} | |
// Update leftBoundary if the current element is outside the range [minK, maxK] | |
if (nums[current] < minK || nums[current] > maxK) { | |
leftBoundary = current; | |
} | |
// Calculate the valid subarray count and add it to the result | |
let a = Math.min(minI, maxI) - leftBoundary; | |
if (a > 0) { | |
ans += a; | |
} | |
} | |
return ans; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment