![]() |
VOOZH | about |
Given a linked list of length n, the task is to determine the maximum distance between two consecutive peaks of the given linked list. A peak is a node with a value greater than its neighbours. The distance between two nodes is defined as the number of nodes present between them.
Examples:
Input: Linked List = 1 -> 2 -> 1 -> 8 -> 6 -> NULL
Output: 1
Explanation: The peaks in the Linked List are 2, 8
The distance between 2 and 8 is 1.
The maximum distance is 1.Input: Linked List = 1 -> 5 -> 3 -> 2 -> 7 -> NULL
Output: 2
Explanation: The peaks in the Linked List are 5, 7
The distance between 5 and 7 is 2.
The maximum distance is 2.
The idea is to iterate over the Linked List and find nodes that are peaks. Keep a record of previous Index that is peak and current index if its a peak.
Follow the steps below to solve the problem:
Below is the implementation of the above approach :
1
Time Complexity: O(n) , where n is the number of nodes.
Space Complexity: O(1)