[LeetCode] Find the Minimum and Maximum Number of Nodes Between Critical Points

2058. Find the Minimum and Maximum Number of Nodes Between Critical Points

A critical point in a linked list is defined as either a local maxima or a local minima.

A node is a local maxima if the current node has a value strictly greater than the previous node and the next node.

A node is a local minima if the current node has a value strictly smaller than the previous node and the next node.

Note that a node can only be a local maxima/minima if there exists both a previous node and a next node.

Given a linked list head, return an array of length 2 containing [minDistance, maxDistance] where minDistance is the minimum distance between any two distinct critical points and maxDistance is the maximum distance between any two distinct critical points. If there are fewer than two critical points, return [-1, -1].

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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
vector<int> nodesBetweenCriticalPoints(ListNode* head) {
vector<int> critical;
int last = head->val, p = 0;
while(head->next) {
int now = head->val, next = head->next->val;
if(last < now and next < now) critical.push_back(p);
else if(now < last and now < next) critical.push_back(p);
p++;
last = head->val;
head = head->next;
}
if(critical.size() < 2) return {-1,-1};
int mi = INT_MAX, ma = critical.back() - critical.front();
for(int i = 0; i < critical.size() - 1; i++) {
mi = min(mi, critical[i+1] - critical[i]);
}
return {mi,ma};
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/10/PS/LeetCode/find-the-minimum-and-maximum-number-of-nodes-between-critical-points/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.