-
Notifications
You must be signed in to change notification settings - Fork 0
/
FindTheMinAndMaxNumberOfNodesBetweenCriticalPoints.java
41 lines (38 loc) · 1.39 KB
/
FindTheMinAndMaxNumberOfNodesBetweenCriticalPoints.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/* https://leetcode.com/problems/find-the-minimum-and-maximum-number-of-nodes-between-critical-points/?envType=daily-question&envId=2024-07-05 */
/* 2058. Find the Minimum and Maximum Number of Nodes Between Critical Points */
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class FindTheMinAndMaxNumberOfNodesBetweenCriticalPoints {
public int[] nodesBetweenCriticalPoints(ListNode head) {
int minDistance = Integer.MAX_VALUE;
int firstMaIndex = -1;
int prevMaIndex = -1;
int index = 1;
ListNode prev = head; // Point to the index 0.
ListNode curr = head.next; // Point to the index 1.
while (curr.next != null) {
if (curr.val > prev.val && curr.val > curr.next.val ||
curr.val < prev.val && curr.val < curr.next.val) {
if (firstMaIndex == -1) // Only assign once.
firstMaIndex = index;
if (prevMaIndex != -1)
minDistance = Math.min(minDistance, index - prevMaIndex);
prevMaIndex = index;
}
prev = curr;
curr = curr.next;
++index;
}
if (minDistance == Integer.MAX_VALUE)
return new int[] {-1, -1};
return new int[] {minDistance, prevMaIndex - firstMaIndex};
}
}