../ Competitive Programming
-rw-r--r--aguang1.4 KiB1 min read

Leet Code Daily 2024-07-05 - Find the Minimum and Maximum Number of Nodes Between Critical Points

Code

c++
/**
 * 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) {
        int min_ans = INT_MAX, max_ans = INT_MIN;
        int first_pos = -1, prev_pos = -1, current_pos = 1;
        for (ListNode* p = head; p->next != nullptr && p->next->next != nullptr;
             p = p->next) {
            int x = p->val, y = p->next->val, z = p->next->next->val;
            if (((x > y) && (z > y)) || ((x < y) && (z < y))) {
                if (prev_pos != -1) {
                    min_ans = min(min_ans, current_pos - prev_pos);
                    max_ans = max(max_ans, current_pos - first_pos);
                }
                prev_pos = current_pos;
                if (first_pos == -1) {
                    first_pos = current_pos;
                }
            }
            current_pos++;
        }
        return vector<int>{
            (min_ans == INT_MAX ? -1 : min_ans),
            (max_ans == INT_MIN ? -1 : max_ans),
        };
    }
};

COMMAND INTERFACE

↑ ↓ navigate · Enter execute · Esc exit · try “whoami”

Loading filesystem…

:help aguang.xyz

A personal website disguised as an operating system.

Ctrl / Cmd + K
Command palette + full-text search
Tab / Shift + Tab
Move between links and controls
Enter
Open a focused link or search result
↑ / ↓ in search
Navigate search results
In a directory filter
Enter/Done or ↓ focuses a result; Esc clears the filter
Esc
Clear a search or close a window