[Leetcode] 2444. Count Subarrays With Fixed Bounds

whitehousechef·2025년 4월 26일

https://leetcode.com/problems/count-subarrays-with-fixed-bounds/description/?envType=daily-question&envId=2025-04-26

initial

I felt this was slidign window but i was thinking of 3 pointers too. But I was thinking to put my "bad pointer", where it points to value outside mink and maxk range to the rightmost index and doing something with left and right pointer.

solution

but if you think, actually we can put the "bad" pointer to our leftmost index as a starting point. And the jmin and jmax pointer should be updated to the index that has values of mink and maxk values.

So the way to count valid subarrays is end index - starting idx +1 if starting idx isnt 0. We know that the end index would be the minimum value of jmax or jmin (our 2 pointers whichever is less in value) cuz even if we need both jmax and jmin for our subarrays to be valid. The starting idx would be jbad +1 and its +1 cuz jbad would be pointing to a bad value so we need to +1 to get a valid value.

so a bit of math like min(jmax,jmin)-(jbad+1)+1 gives us min(jmax,jmin)-jbad. This is the range of starting point of our subarrays. So we can just add that. But we cannot blindly just add that cuz if jbad is getting big in value cuz we still havent found a valid jmax or jmin, then that answer would be a negative value. To consider that case, we do a max(0, that_val) to add 0 to result when we iterate through the num if we havent found a valid case

complexity

n time
1 space

0개의 댓글