From c02a481db22b3565cc9a23e7f3edd574d3700e07 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 2 Jun 2024 11:23:53 +0200 Subject: [PATCH] =?UTF-8?q?swift:=20add=20=C2=AB901.=20Online=20Stock=20Sp?= =?UTF-8?q?an=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- swift/online-stock-span.swift | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 swift/online-stock-span.swift diff --git a/swift/online-stock-span.swift b/swift/online-stock-span.swift new file mode 100644 index 0000000..95e64fa --- /dev/null +++ b/swift/online-stock-span.swift @@ -0,0 +1,23 @@ +class StockSpanner { + private var st: [(Int, Int)] = [] + + init() {} + + func next(_ price: Int) -> Int { + var span = 1 + while !st.isEmpty && st.last!.0 <= price { + span += st.last!.1 + st.removeLast() + } + + st.append((price, span)) + + return span + } +} + +/** + * Your StockSpanner object will be instantiated and called as such: + * let obj = StockSpanner() + * let ret_1: Int = obj.next(price) + */