Shohei Yoshida
Shohei Yoshida's Blog

Shohei Yoshida's Blog

LeetCode 948. Bag of Tokens in F#

Shohei Yoshida's photo
Shohei Yoshida
·Sep 12, 2022·

1 min read

URL

leetcode.com/problems/bag-of-tokens

Code

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

let bagOfTokensScore (tokens: int list) (power: int) : int =
    let rec bagOfTokensScore' left right (tokens: int []) power score ret =
        if left > right then
            ret
        elif power >= tokens.[left] then
            let score' = score + 1
            bagOfTokensScore' (left + 1) right tokens (power - tokens.[left]) score' (System.Math.Max(ret, score + 1))
        elif score >= 1 then
            bagOfTokensScore' left (right - 1) tokens (power + tokens.[right]) (score - 1) ret
        else
            ret

    let tokens' = tokens |> List.sort |> List.toArray
    bagOfTokensScore' 0 (tokens'.Length - 1) tokens' power 0 0
 
Share this