From d34c3e5b3da36ed41311606eded292d8d2c9cea6 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Fri, 5 Jul 2024 13:20:26 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB2058.=20Find=20the=20Minimum?= =?UTF-8?q?=20and=20Maximum=20Number=20of=20Nodes=20Between=20Critical=20P?= =?UTF-8?q?oints=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...number-of-nodes-between-critical-points.go | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 go/find-the-minimum-and-maximum-number-of-nodes-between-critical-points.go diff --git a/go/find-the-minimum-and-maximum-number-of-nodes-between-critical-points.go b/go/find-the-minimum-and-maximum-number-of-nodes-between-critical-points.go new file mode 100644 index 0000000..3093791 --- /dev/null +++ b/go/find-the-minimum-and-maximum-number-of-nodes-between-critical-points.go @@ -0,0 +1,36 @@ +package main + +func nodesBetweenCriticalPoints(head *ListNode) []int { + OUT_OF_BOUNDS_DISTANCE := 1000000 + + isCritical := func(x, y, z int) bool { + return (y < x && y < z) || (y > x && y > z) + } + + minDistance := OUT_OF_BOUNDS_DISTANCE + + previous, node := head, head.Next + previousIdx, firstIdx := 0, 0 + + index := 1 + for node.Next != nil { + if isCritical(previous.Val, node.Val, node.Next.Val) { + if previousIdx == 0 { + firstIdx = index + } else { + minDistance = min(minDistance, index-previousIdx) + } + + previousIdx = index + } + + index++ + previous, node = node, node.Next + } + + if minDistance != OUT_OF_BOUNDS_DISTANCE { + return []int{minDistance, previousIdx - firstIdx} + } + + return []int{-1, -1} +}