LeetCode 2962. Count Subarrays Where Max Element Appears at Least K Times in F#

URL

Count Subarrays Where Max Element Appears at Least K Times - LeetCode

Code

https://github.com/syohex/dotnet-study/tree/master/fsharp/leetcode/challenge/202403/count_subarrays_where_max_element_appears_at_least_k_times/main.fsx

let countSubarrays (nums: int list) (k: int) : int =
    let rec moveLeft (nums: int[]) left max count =
        if count < k || left >= nums.Length then
            left, count
        else if nums.[left] = max then
            moveLeft nums (left + 1) max (count - 1)
        else
            moveLeft nums (left + 1) max count

    let rec countSubarrays' (nums: int[]) left right count max acc =
        if right >= nums.Length then
            acc
        else
            let count' = if nums.[right] = max then count + 1 else count
            let left', count' = moveLeft nums left max count'
            countSubarrays' nums left' (right + 1) count' max (acc + left')

    let max = List.max nums
    countSubarrays' (List.toArray nums) 0 0 0 max 0