2962. Count Subarrays Where Max Element Appears at Least K Times

TBD

```java
class Solution {
    public long countSubarrays(int[] A, int k) {
        int max = 0;
        for (int num : A) {
            max = Math.max(max, num);
        }

        int right = 0;
        int left = 0;
        int count = 0;
        long result = 0;

        while (right < A.length) {
            int rightNum = A[right];
            if (rightNum == max) {
                count++;
            }
            right++;

            while (left < right && count >= k) {
                int leftNum = A[left];
                if (leftNum == max) {
                    count--;
                }
                left++;
            }
            // this has to think clearly!
            result += left; // 4(right) - 2(right-left) = 2, 5 -  1 = 4
        }
        return result;
    }
}
/**

T: O(n)
S: O(1)

4

5 - 3 = 2

 0 1 2 3 4 
       x
[1,3,2,3,3] 
         j
         i     
       j
     i
[1,3,2,3]
   [3,2,3] means last [i to j] can't count -> so len 4(j+1) - 2(j-i+1) = 2 = i

[1,3,2,3,3]
[3,2,3,3]
[2,3,3]
[3,3] means last [i to j] can't count, so len 5(j+1) - 1(j - i + 1) = 4 = i

     2 +    

[1,3,2,3,3]
[         ]

*/
```

Last updated