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} +}