LeetCode 1381. Design a Stack With Increment Operation in F#
URL
Design a Stack With Increment Operation - LeetCode
Code
type CustomStack =
{ Data: int[]
Top: int }
static member Init(maxSize: int) : CustomStack =
{ Data = Array.zeroCreate maxSize
Top = -1 }
static member Push (x: int) (s: CustomStack) : CustomStack =
if s.Top + 1 < s.Data.Length then
let top = s.Top + 1
s.Data.[top] <- x
{ s with Data = s.Data; Top = top }
else
s
static member Pop(s: CustomStack) : int * CustomStack =
if s.Top >= 0 then
let ret = s.Data.[s.Top]
ret, { s with Top = s.Top - 1 }
else
-1, s
static member Increment (k: int) (v: int) (s: CustomStack) : CustomStack =
let len = min k (s.Top + 1)
seq { 0 .. (len - 1) } |> Seq.iter (fun i -> s.Data.[i] <- s.Data.[i] + v)
{ s with Data = s.Data }