LeetCode 2762. Continuous Subarrays in F#

URL

https://leetcode.com/problems/continuous-subarrays/description/?envType=daily-question&envId=2024-12-14

Code

https://github.com/syohex/dotnet-study/blob/master/fsharp/leetcode/challenge/202412/continuous_subarrays/main.fsx

#r "nuget:FSharpx.Collections"

open FSharpx.Collections

let continuousSubarray (nums: int list) : int64 =
    let rec updateQueue index q = 
        match PriorityQueue.tryPop q with
        | None -> q
        | Some(((_, i), q')) ->
            if i < index then
                updateQueue index q'
            else
                q

    let rec updateWindow left right minQ maxQ =
        if left >= right then
            left, minQ, maxQ
        else
            let min, _ = PriorityQueue.peek minQ
            let max, _ = PriorityQueue.peek maxQ

            if max - min <= 2 then
                left, minQ, maxQ
            else
                let left = left + 1
                let minQ = updateQueue left minQ
                let maxQ = updateQueue left maxQ
                updateWindow left right minQ maxQ

    let rec continuousSubarray' nums left minQ maxQ acc =
        match nums with
        | [] -> acc
        | (right, h) :: t ->
            let minQ = PriorityQueue.insert (h, right) minQ
            let maxQ = PriorityQueue.insert (h, right) maxQ

            let left, minQ, maxQ = updateWindow left right minQ maxQ
            let acc = acc + (int64 <| right - left + 1)
            continuousSubarray' t left minQ maxQ acc

    let nums = nums |> List.indexed
    let minQ = PriorityQueue.empty false
    let maxQ = PriorityQueue.empty true
    continuousSubarray' nums 0 minQ maxQ 0L