VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-distance-between-peaks-in-given-linked-list/

⇱ Maximum distance between Peaks in given Linked List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum distance between Peaks in given Linked List

Last Updated : 23 Jul, 2025

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.

[Expected Approach] Using Greedy Technique - O(n) Time and O(1) Space

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:

  • Initialize pointers prev, curr (previous index, current index).
  • Traverse the list with curr pointer.
  • Check peak conditions and update the maximum distance if conditions are satisfied.
  • Update pointers and current Index.
  • Print maximum distance after traversal.

Below is the implementation of the above approach :


Output
1

Time Complexity: O(n) , where n is the number of nodes.
Space Complexity: O(1)

Comment