Photo by Priscilla Du Preez ๐จ๐ฆ on Unsplash
2058. Find the Minimum and Maximum Number of Nodes Between Critical Points
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:
def getNext(node):
if node.next:
return node.next.val
return node.val
lastStep = None
minDist = float('inf')
maxDist = -1
firstStep = None
def travel(node, prev, step):
nonlocal minDist, maxDist, lastStep, firstStep
if node:
val = node.val
nextVal = getNext(node)
if (val > prev and val > nextVal) or (val < prev and val < nextVal):
if lastStep:
minDist = min(minDist, step - lastStep)
maxDist = max(maxDist, step - firstStep)
else:
firstStep = step
lastStep = step
travel(node.next, node.val, step + 1)
travel(head, head.val, 1)
return [minDist if minDist != float('inf') else -1, maxDist]
ย