# Generate Linked List consisting of maximum difference of squares of pairs of nodes from given Linked List

Given a Linked List of even number of nodes, the task is to generate a new Linked List such that it contains the maximum difference of squares of node values in decreasing order by including each node in a single pair.

Examples:

Input: 1 -> 6 -> 4 -> 3 -> 5 ->2
Output: 35 -> 21 -> 7
Explanation:
The difference between squares of 6 and 1 forms the first node with value 35.
Difference between squares of 5 and 2 forms the second node with value 21.
Difference between squares of 4 and 3 forms the third node with value 7.
Therefore, the formed LL is 35 -> 21 -> 7.

Input: 2 -> 4 -> 5 -> 3 -> 7 -> 8 -> 9 -> 10
Output: 96 -> 72 -> 48 -> 10
Explanation:
The difference between squares of 10 and 2 forms the first node with value 96.
Difference between squares of 9 and 3 forms the second node with value 72.
Difference between squares of 8 and 4 forms the third node with value 48.
Difference between squares of 7 and 5 forms the fourth node with value 10.
Therefore, the formed LL is 96 -> 72 -> 48 -> 10.

Approach: The approach is to find the maximum value of a node and always make the difference between the largest and the smallest node value. So create a deque and insert all nodes value in it, and sort the deque. Now, access the largest and smallest values from both the ends. Below are the steps:

• Create a deque and insert all nodes value in the deque.
• Sort the deque to get the largest node value and smallest node value in constant time.
• Create another linked list having value difference of square’s of the largest and the smallest value from the back and the front of the deque respectively.
• After each iteration pop both the smallest and largest value from the deque.
• After the above steps, print the nodes of the new Linked List formed.

Below is the implementation of the above approach:

Output:
35 21 7

Time Complexity: O(N*log N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

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.

Article Tags :