I’m counting subarrays where the sum is <= k using a sliding window, but some cases come out too high. I expected this to work for all integer arrays, but negatives seem to break it. What assumption is invalid here, and what’s the right approach?
function countAtMost(nums, k) {
let left = 0, sum = 0, count = 0;
for (let right = 0; right < nums.length; right++) {
sum += nums[right];
while (sum > k) sum -= nums[left++];
count += right - left + 1;
}
return count;
}
console.log(countAtMost([3, -2, 4], 4));
Sora