Maximum and Minimum element of a linked list which is divisible by a given number k

Given a singly linked list of nodes. Find the smallest and largest elements in linked list divisible by a given number .

Examples:

Input : List = 15 -> 14 -> 13 -> 22 -> 50
K = 5
Output :
Maximum element in linked list divisible by K: 50
Minimum element in linked list divisible by K: 5

Input : List = 10 -> 14 -> 13 -> 22 -> 100
K = 10
Output :
Maximum element in linked list divisible by K: 100
Minimum element in linked list divisible by K: 10

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach:

• The idea is to traverse the linked list to the end and initialize the max and min variable to INT_MIN and INT_MAX respectively.
• After that check a condition that if the max value is less then the current node’s value and divisible by K then current node’s value is assigned to max.
• Similarly check if the current node’s value is less than min value and divisible by k then the current node’s value is assigned to min. Repeat above two steps until the end of the list is reached.

Below is the implementation of the above approach:

C#

Output:

Max Element : 50
Min Element : 5

Time complexity : O(n)

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.