Shohei Yoshida
Shohei Yoshida's Blog

Shohei Yoshida's Blog

LeetCode 1642. Furthest Building You Can Reach in F#

Shohei Yoshida's photo
Shohei Yoshida
·Jun 21, 2022·

1 min read

URL

leetcode.com/problems/furthest-building-you..

Code

github.com/syohex/dotnet-study/blob/master/..

#r "nuget:FSharpx.Collections"

open FSharpx.Collections

let furthestBuilding (heights: int list) (bricks: int) (ladders: int) : int =
    let rec furthestBuilding' (q: IPriorityQueue<int>) qLen prev i heights bricks ladders =
        match heights with
        | [] -> i
        | h :: t ->
            let diff = h - prev

            if diff <= 0 then
                furthestBuilding' q qLen h (i + 1) t bricks ladders
            else
                let q' = PriorityQueue.insert diff q
                let qLen' = qLen + 1

                if qLen' <= ladders then
                    furthestBuilding' q' qLen' h (i + 1) t bricks ladders
                else
                    let min, q'' = PriorityQueue.pop q'
                    let bricks' = bricks - min

                    if bricks' < 0 then
                        i
                    else
                        furthestBuilding' q'' qLen h (i + 1) t bricks' ladders

    let q = PriorityQueue.empty false
    furthestBuilding' q 0 heights.Head 0 heights.Tail bricks ladders
 
Share this