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)
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.
- Generate Linked List consisting of maximum difference of squares of pairs of nodes from given Linked List
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Check if absolute difference of consecutive nodes is 1 in Linked List
- Find the string formed by joining k consecutive nodes of linked list
- Maximum sum contiguous nodes in the given linked list
- Delete N nodes after M nodes of a linked list
- Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
- Splitting starting N nodes into new Circular Linked List while preserving the old nodes
- Create new linked list from two given linked list with greater element at each node
- Sum and Product of all even digit sum Nodes of a Singly Linked List
- Sum and Product of nodes with value as even digit sum in Circular Linked List
- Find the sum of last n nodes of the given Linked List
- Sum of all nodes in a doubly linked list divisible by a given number K
- Sum of distances between the two nearest perfect squares to all the nodes of the given linked list
- Delete continuous nodes with sum K from a given linked list
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Merge a linked list into another linked list at alternate positions
- Convert singly linked list into circular linked list
- Difference between Singly linked list and Doubly 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.