LeetCode 058. Find the Minimum and Maximum Number of Nodes Between Critical Points in F#

URL

Find the Minimum and Maximum Number of Nodes Between Critical Points - LeetCode

Code

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

type ListNode =
    | Leaf
    | Node of int * ListNode

let nodesBetweenCriticalPoints (head: ListNode) : (int * int) =
    let rec nodesBetweenCriticalPoints' node i firstCritical prevCritical minDistance =
        match node with
        | Leaf
        | Node(_, Leaf)
        | Node(_, Node(_, Leaf)) ->
            if firstCritical = prevCritical then
                -1, -1
            else
                minDistance, prevCritical - firstCritical
        | Node(prev, current) ->
            match current with
            | Leaf
            | Node(_, Leaf) -> failwith "never reach here"
            | Node(v, Node(next, _)) ->
                let isMaxima = prev < v && v > next
                let isMinima = prev > v && v < next

                if isMaxima || isMinima then
                    if firstCritical = 0 then
                        nodesBetweenCriticalPoints' current (i + 1) i i minDistance
                    else
                        nodesBetweenCriticalPoints' current (i + 1) firstCritical i (min minDistance (i - prevCritical))
                else
                    nodesBetweenCriticalPoints' current (i + 1) firstCritical prevCritical minDistance

    nodesBetweenCriticalPoints' head 1 0 0 System.Int32.MaxValue