Given a linked list, the task is tofind the maximum sum obtained by adding any k consecutive nodes of linked list.
Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL, K = 5
Maximum sum is obtained by adding last 5 nodes
Input: 2 -> 5 -> 3 -> 6 -> 4 -> 1 -> 7 -> NULL, K = 4
Approach: The idea is to use a sliding window of size k, keep track of sum of current window and update maximum sum if required. To implement sliding window two pointers can be used to represent starting and ending point. At each step first the value of node pointed by start is subtracted from current sum and the value of node pointed by end is added to current sum. This sum is compared to maximum sum and result is updated if required. The start and end pointers are incremented by one at each step.
Below is the implementation of above approach:
Time Complexity: O(n)
Auxiliary Space: O(1)
- Check if absolute difference of consecutive nodes is 1 in Linked List
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Maximum sum contiguous nodes in the given linked list
- Splitting starting N nodes into new Circular Linked List while preserving the old nodes
- Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
- Delete N nodes after M nodes of a linked list
- Linked List Sum of Nodes Between 0s
- Sum of the nodes of a Singly Linked List
- Sum and Product of all the nodes which are less than K in the linked list
- Linked List Product of Nodes Between 0s
- Find the sum of last n nodes of the given Linked List
- Sum of the alternate nodes of linked list
- Sum of all odd frequency nodes of the Linked List
- Sum of the nodes of a Circular Linked List
- Find sum of even and odd nodes in a linked list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.