본문 바로가기
LeetCode/Sliding Window

[LeetCode][Kotlin] 2962. Count Subarrays Where Max Element Appears at Least K Times

by jinwo_o 2024. 11. 16.

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

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.

 

subarray is a contiguous sequence of elements within an array.

정수 배열 nums와 양의 정수 k가 주어집니다. 

nums의 최대 요소가 해당 하위 배열에 최소 k번 나타나는 하위 배열의 개수를 반환합니다. 

하위 배열은 배열 내의 연속된 요소 시퀀스입니다.

 

Example 1:

Input: nums = [1,3,2,3,3], k = 2

Output: 6

Explanation: The subarrays that contain the element 3 at least 2 times are: [1,3,2,3], [1,3,2,3,3], [3,2,3], [3,2,3,3], [2,3,3] and [3,3].

 

Example 2:

Input: nums = [1,4,2,1], k = 3

Output: 0

Explanation: No subarray contains the element 4 at least 3 times.

 

Constraints:

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^6
  • 1 <= k <= 10^5

코드

  • Example 1 : [1, 3, 2, 3], [3, 2, 3] / [(1, 3, 2, 3), 3], [(3, 2, 3), 3]), [2, 3, 3], [3, 3]
class Solution {
    fun countSubarrays(nums: IntArray, k: Int): Long {
        var maxN = nums.max()
        var maxCnt = 0
        var l = 0
        var res = 0L

        for (r in nums.indices) {
            if (nums[r] == maxN) {
                maxCnt += 1
            }

            while (maxCnt == k) {
                if (nums[l] == maxN) {
                    maxCnt -= 1
                }
                
                l++
            }
            
            res += l
        }

        return res
    }
}