Open In App

Maximum distance between Peaks in given Linked List

Last Updated : 30 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 :

C++
// C++ code to find the maximum distance 
// between consecutive peaks in a linked list

#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* next;

    Node(int new_data) {
        data = new_data;
        next = nullptr;
    }
};

// Function to find the maximum distance
void findMaxGap(Node* head) {

    // Prev points to previous of current node
    Node* prev = new Node(-1);
    prev->next = head;

    // Current is initially head
    Node* curr = head;
    int lastIndex = -1, currentIndex = 0;
    int maxGap = 0, gap = 0;

    // Loop till current is not NULL
    while (curr != nullptr) {

        // Find next of current
        Node* next = curr->next;

        // One node only
        if (prev->next == head && next == nullptr) {
            cout << maxGap;
            return;
        }

        // For the 1st node check only next
        else if (prev->next == head 
                 && next->data < curr->data) {

            // Update lastIndex if first node is a peak
            lastIndex = currentIndex;
        }

        // For the last node check only the prev node
        else if (next == nullptr && prev->data < curr->data) {

            // Update lastIndex if last node is a peak
            if (lastIndex != -1) {
                lastIndex = currentIndex;
            } else {
                // Calculate gap and update maxGap
                gap = currentIndex - lastIndex - 1;
                maxGap = max(gap, maxGap);
                lastIndex = currentIndex;
            }
        }

        // Check prev and next nodes for intermediate nodes
        else if (prev->data < curr->data 
                 && next->data < curr->data) {

            // Update lastIndex if current node is a peak
            if (lastIndex != -1) {
                lastIndex = currentIndex;
            } else {
                // Calculate gap and update maxGap
                gap = currentIndex - lastIndex - 1;
                maxGap = max(gap, maxGap);
                lastIndex = currentIndex;
            }
        }

        // Move prev and curr pointer
        prev = prev->next;
        curr = curr->next;
        currentIndex++;
    }

    cout << maxGap << "\n";
}

int main() {
  
    // Create a hard-coded linked list:
    // 1-> 2 -> 1 -> 8 -> 6 -> NULL
    Node* head = new Node(1);
    head->next = new Node(2);
    head->next->next = new Node(1);
    head->next->next->next = new Node(8);
    head->next->next->next->next = new Node(6);

    findMaxGap(head);
}
C
// C code to find the maximum distance 
//between consecutive peaks in a linked list

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* next;
};

struct Node* createNode(int data, struct Node* next) {
    struct Node* newNode = 
      	(struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = next;
    return newNode;
}

// Function to find the maximum distance
void findMaxGap(struct Node* head) {

    // Prev points to previous of current node
    struct Node* prev = createNode(-1, head);

    // Current is initially head
    struct Node* curr = head;
    int lastIndex = -1, currentIndex = 0;
    int maxGap = 0, gap = 0;

    // Loop till current is not NULL
    while (curr != NULL) {

        // Find next of current
        struct Node* next = curr->next;

        // One node only
        if (prev->next == head && next == NULL) {
            printf("%d\n", maxGap);
            return;
        }

        // For the 1st node check only next
        else if (prev->next == head &&
                 next->data < curr->data) {

            // Update lastIndex if first node is a peak
            lastIndex = currentIndex;
        }

        // For the last node check only the prev node
        else if (next == NULL &&
                 prev->data < curr->data) {

            // Update lastIndex if last node is a peak
            if (lastIndex != -1) {
                lastIndex = currentIndex;
            } else {

                // Calculate gap and update maxGap
                gap = currentIndex - lastIndex - 1;
                maxGap = (gap > maxGap) ? gap : maxGap;
                lastIndex = currentIndex;
            }
        }

        // Check prev and next nodes for intermediate nodes
        else if (prev->data < curr->data &&
                 next->data < curr->data) {

            // Update lastIndex if current node is a peak
            if (lastIndex != -1) {
                lastIndex = currentIndex;
            } else {

                // Calculate gap and update maxGap
                gap = currentIndex - lastIndex - 1;
                maxGap = (gap > maxGap) ? gap : maxGap;
                lastIndex = currentIndex;
            }
        }

        // Move prev and curr pointer
        prev = prev->next;
        curr = curr->next;
        currentIndex++;
    }

    // Print the maximum gap
    printf("%d\n", maxGap);
}

int main() {
    
     // Create a hard-coded linked list:
    // 1-> 2 -> 1 -> 8 -> 6 -> NULL
    struct Node* head = createNode(1, NULL);
    head->next = createNode(2, NULL);
    head->next->next = createNode(1, NULL);
    head->next->next->next = createNode(8, NULL);
    head->next->next->next->next = createNode(6, NULL);
  
    findMaxGap(head);

    return 0;
}
Java
// Java code to find the maximum distance
// between consecutive peaks in a linked list
class Node {
    int data;
    Node next;

    Node(int new_data) {
        data = new_data;
        next = null;
    }
}

public class GfG {

    // Function to find the maximum distance between peaks
    static void findMaxGap(Node head) {

        // Initialize pointers and variables
        Node prev = new Node(-1);
        prev.next = head;
        Node curr = head;
        int lastIndex = -1, currentIndex = 0;
        int maxGap = 0, gap = 0;

        // Loop until current node is null
        while (curr != null) {
            Node next = curr.next;

            // Check if the current node is a peak
            boolean isPeak = (prev.data < curr.data)
                             && (next == null
                                 || next.data < curr.data);

            if (isPeak) {
                if (lastIndex != -1) {
                  
                    // Calculate gap and update maxGap
                    gap = currentIndex - lastIndex - 1;
                    maxGap = Math.max(gap, maxGap);
                }
                lastIndex = currentIndex;            
            }

            // Move prev and curr pointers
            prev = prev.next;
            curr = curr.next;
            currentIndex++;
        }

        // Print the maximum gap between peaks
        System.out.println(maxGap);
    }

    public static void main(String[] args) {
      
        // Create a hard-coded linked list: 1 -> 2 -> 1 -> 8
        // -> 6 -> NULL
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(1);
        head.next.next.next = new Node(8);
        head.next.next.next.next = new Node(6);

        findMaxGap(head);
    }
}
Python
# Python code to find the maximum distance 
# between peaks in a linked list

class Node:
    def __init__(self, new_data):
        self.data = new_data
        self.next = None

def find_max_gap(head):

    # Prev points to previous of current node
    prev = Node(-1)
    prev.next = head

    # Current is initially head
    curr = head
    last_index = -1
    current_index = 0
    max_gap = 0
    gap = 0

    # Loop till current is not None
    while curr is not None:

        # Find next of current
        next_node = curr.next

        # One node only
        if prev.next == head and next_node is None:
            print(max_gap)
            return

        # For the 1st node check only next
        elif prev.next == head and \
             next_node.data < curr.data:

            # Update last_index if first node is a peak
            last_index = current_index

        # For the last node check only the prev node
        elif next_node is None and \
             prev.data < curr.data:

            # Update last_index if last node is a peak
            if last_index != -1:
                last_index = current_index
            else:
                # Calculate gap and update max_gap
                gap = current_index - last_index - 1
                max_gap = max(gap, max_gap)
                last_index = current_index

        # Check prev and next nodes for intermediate nodes
        elif prev.data < curr.data and \
             next_node.data < curr.data:

            # Update last_index if current node is a peak
            if last_index != -1:
                last_index = current_index
            else:
                # Calculate gap and update max_gap
                gap = current_index - last_index - 1
                max_gap = max(gap, max_gap)
                last_index = current_index

        # Move prev and curr pointer
        prev = prev.next
        curr = curr.next
        current_index += 1

    print(max_gap)

if __name__ == "__main__":

    # Create a hard-coded linked list:
    # 1-> 2 -> 1 -> 8 -> 6 -> NULL
    head = Node(1)
    head.next = Node(2)
    head.next.next = Node(1)
    head.next.next.next = Node(8)
    head.next.next.next.next = Node(6)
    
    find_max_gap(head)
C#
// C# code to find the maximum distance 
// between peaks in a linked list

using System;

class Node {
    public int Data;
    public Node Next;

    public Node(int newData) {
        Data = newData;
        Next = null;
    }
}

class GfG {

    // Function to find the maximum distance
    static void FindMaxGap(Node head) {

        // Initialize prev with a dummy node
        Node prev = new Node(-1);
        prev.Next = head;

        // Current is initially head
        Node curr = head;
        int lastIndex = -1, currentIndex = 0;
        int maxGap = 0, gap = 0;

        // Loop till current is not null
        while (curr != null) {

            // Find next of current
            Node next = curr.Next;

            // One node only
            if (prev.Next == head && next == null) {
                Console.WriteLine(maxGap);
                return;
            }

            // For the 1st node check only next
            else if (prev.Next == head &&
                     next.Data < curr.Data) {

                // Update lastIndex if first node is a peak
                lastIndex = currentIndex;
            }

            // For the last node check only the prev node
            else if (next == null &&
                     prev.Data < curr.Data) {

                // Update lastIndex if last node is a peak
                if (lastIndex != -1) {
                    lastIndex = currentIndex;
                } else {

                    // Calculate gap and update maxGap
                    gap = currentIndex - lastIndex - 1;
                    maxGap = Math.Max(gap, maxGap);
                    lastIndex = currentIndex;
                }
            }

            // Check prev and next nodes for intermediate nodes
            else if (prev.Data < curr.Data &&
                     next.Data < curr.Data) {

                // Update lastIndex if current node is a peak
                if (lastIndex != -1) {
                    lastIndex = currentIndex;
                } else {

                    // Calculate gap and update maxGap
                    gap = currentIndex - lastIndex - 1;
                    maxGap = Math.Max(gap, maxGap);
                    lastIndex = currentIndex;
                }
            }

            // Move prev and curr pointer
            prev = prev.Next;
            curr = curr.Next;
            currentIndex++;
        }

        Console.WriteLine(maxGap);
    }

    static void Main(string[] args) {

         // Create a hard-coded linked list:
         // 1-> 2 -> 1 -> 8 -> 6 -> NULL
        Node head = new Node(1);
        head.Next = new Node(2);
        head.Next.Next = new Node(1);
        head.Next.Next.Next = new Node(8);
        head.Next.Next.Next.Next = new Node(6);

        FindMaxGap(head);
    }
}
JavaScript
// JavaScript code to find the maximum distance
// between peaks in a linked list
class Node {
    constructor(newData) {
        this.data = newData;
        this.next = null;
    }
}

function findMaxGap(head) {

    // Prev points to previous of current node
    let prev = new Node(-1);
    prev.next = head;

    // Current is initially head
    let curr = head;
    let lastIndex = -1, currentIndex = 0;
    let maxGap = 0, gap = 0;

    // Loop till current is not null
    while (curr !== null) {

        // Find next of current
        let next = curr.next;

        // One node only
        if (prev.next === head && next === null) {
            console.log(maxGap);
            return;
        }

        // For the 1st node check only next
        if (prev.next === head && next.data < curr.data) {
            lastIndex = currentIndex;
        }
        else if (next === null && prev.data < curr.data) {
        
            // For the last node check only the prev node
            if (lastIndex !== -1) {
                lastIndex = currentIndex;
            }
            else {
            
                // Calculate gap and update maxGap
                gap = currentIndex - lastIndex - 1;
                maxGap = Math.max(gap, maxGap);
                lastIndex = currentIndex;
            }
        }
        else if (prev.data < curr.data
                 && next.data < curr.data) {
                 
            // Check prev and next nodes for nodes
            if (lastIndex !== -1) {
                lastIndex = currentIndex;
            }
            else {
            
                // Calculate gap and update maxGap
                gap = currentIndex - lastIndex - 1;
                maxGap = Math.max(gap, maxGap);
                lastIndex = currentIndex;
            }
        }

        // Move prev and curr pointer
        prev = prev.next;
        curr = curr.next;
        currentIndex++;
    }

    // Print the maximum gap
    console.log(maxGap);
}

// Create a hard-coded linked list:
// 1-> 2 -> 1 -> 8 -> 6 -> NULL
let head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(1);
head.next.next.next = new Node(8);
head.next.next.next.next = new Node(6);

findMaxGap(head);

Output
1

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



Next Article
Article Tags :
Practice Tags :

Similar Reads