-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindtheMinimumAndMaximumNumberOfNodesBetweenCriticalPoints.cpp
More file actions
74 lines (64 loc) · 1.79 KB
/
findtheMinimumAndMaximumNumberOfNodesBetweenCriticalPoints.cpp
File metadata and controls
74 lines (64 loc) · 1.79 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <iostream>
#include <vector>
#include <limits.h>
#include <algorithm>
using namespace std;
// 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
{
private:
ListNode *head;
ListNode *current;
public:
//* default constructor
Solution() : head(nullptr) {}
vector<int> nodesBetweenCriticalPoints(ListNode *head)
{
vector<int> criticalPoints;
// vector<int> result;
int index = 1; // Start with 1 as we skip the first node
ListNode *prev = head;
ListNode *current = head->next;
while (current->next != nullptr)
{
ListNode *next = current->next;
if ((current->val > prev->val && current->val > next->val) ||
(current->val < prev->val && current->val < next->val))
{
criticalPoints.push_back(index);
}
prev = current;
current = next;
index++;
}
if (criticalPoints.size() < 2)
{
return {-1, -1};
}
sort(criticalPoints.begin(), criticalPoints.end());
int maxDist = criticalPoints[criticalPoints.size() - 1] - criticalPoints[0];
// setting minDist to the greatest value to make sure
// there is a less mininum value than it and to be compared right with all testcases
int minDist = INT_MAX; //* we should use preprocessor directive "limits.h"
for (auto i = 1; i < criticalPoints.size(); i++)
{
//! updating minDist with the minimum of every 2 point subtraction
minDist = min(minDist, criticalPoints[i] - criticalPoints[i - 1]);
}
// result.push_back(minDist);
// result.push_back(maxDist);
return {minDist, maxDist};
}
};
int main()
{
return 0;
}