Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created April 29, 2025 17:40
Show Gist options
  • Save tatsuyax25/cfa7e820c5e7fe1d120b3aa08c21562f to your computer and use it in GitHub Desktop.
Save tatsuyax25/cfa7e820c5e7fe1d120b3aa08c21562f to your computer and use it in GitHub Desktop.
You are given an integer array nums and a positive integer k. Return the number of subarrays where the maximum element of nums appears at least k times in that subarray. A subarray is a contiguous sequence of elements within an array.
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var countSubarrays = function(nums, k) {
// Initialize an array to store the indices of the maximum elements and a variable to store the maximum element
let indices = [], max = 0;
// Iterate over the nums array
for (let i = 0; i < nums.length; i++) {
// If the current number is greater than max, update max and reset indices
if (nums[i] > max) {
indices = [i];
max = nums[i];
}
// If the current number is equal to max, add its index to indices
else if (nums[i] === max) {
indices.push(i);
}
}
// Initialize a variable to store the count of valid subarrays and a pointer to the left end of the current subarray
let count = 0, leftPtr = 0;
// Iterate over the indices array while there are at least k elements to the right of leftPtr
while (leftPtr <= indices.length - k) {
// Calculate the count of subarrays ending at the right end of the current subarray
const currCount = indices[leftPtr] + 1;
// Calculate the index of the right end of the current subarray
const rightPtr = leftPtr + k - 1;
// Calculate the index of the next maximum element or the end of nums if there is no next maximum element
let nextPtr = rightPtr + 1 >= indices.length ? nums.length : indices[rightPtr + 1];
// Calculate the count of subarrays starting at the next maximum element or the end of nums if there is no next maximum element
let nextCount = nextPtr - indices[rightPtr] - 1;
// Add the count of valid subarrays in the current subarray to count
count += currCount + (currCount * nextCount);
// Move the left end of the current subarray to the right
leftPtr++;
}
// Return the count of valid subarrays
return count;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment