Maximum distance between Peaks in given Linked List
Given a linked list lis of length N, the task is to determine the maximum distance between two consecutive peaks of the given linked list. A peak is defined as a node having a value greater than its neighbours. The distance between two nodes is defined as the number of nodes present between them.
Input: lis = 1 -> 2 -> 3 -> 1 -> 5 -> 4 -> 4 -> 10 -> 7
Explanation: The peaks in the linkedlist are 3, 5, 10
The distance between 3 and 5 is 1.
The distance between 5 and 10 is 2.
The maximum distance is 2.
Input: lis = 1 -> 3 -> 1 -> 1 ->1 -> 1 -> 4 -> 2 -> 7
Explanation: The peaks in the linkedlist are 3, 4, 7
The distance between 3 and 4 is 4.
The distance between 4 and 7 is 1.
The maximum distance is 4.
Approach: The solution is based on greedy approach. Follow the steps mentioned below to solve the problem:
- Iterate over the linkedlist and find nodes that are peaks.
- Keep a record of previousIndex that is peak and current index if its a peak
Below is the implementation of the above approach.
Time Complexity: O(N)
Auxiliary Space: O(N)