Find the Max sum of Subarray of length K in a Linked List
Given a linked list of integers and a number K, find the maximum sum of a subarray of length K.
Examples:
Input: List = 1 -> -2 -> 3 -> 4 -> -1 -> 2, K = 3
Output: 6
Explanation: The sum of subarray 3 -> 4 -> -1 is 6 which is the maximum sum of a subarray of length K = 3
Input: List = -1 -> 2 -> 3 -> -4 -> 5 -> 6, K = 2
Output: 11
Explanation: The maximum sum of a subarray of length K = 2 is 11.
Naive Approach: The brute-force approach to find the maximum sum of a subarray of length K in a linked list would be to generate all possible subarrays of length K and compute their sums, then return the maximum sum.
Time complexity: O(n * K2), where n is the number of nodes in the linked list. This is because we would need to generate subarrays of length K for each node in the linked list, and computing the sum of each subarray would take O(K) time.
Auxiliary Space: O(1)
Efficient Approach: To solve the problem follow the below idea:
The idea is to use the sliding window algorithm to efficiently compute the maximum sum of the subarray of a given length in a linked list. By maintaining a running sum and sliding the window forward one node at a time, we can calculate the sum of each subarray and update the maximum sum as we traverse the linked list.
Below are the steps for the above approach:
- Initialize two pointers, start and end, to the head of the linked list.
- Initialize curSum and maxSum to 0.
- Run a loop from i = 0 till i < k and end != NULL to compute the sum of the first k elements in the linked list add the value of the current node to currSum and set end to the next node,
- currSum += end -> data, end = end -> next.
- Set maxSum equal to currSum.
- Use a while loop to slide the window over the linked list till the end != NULL,
- Add the value of the node that falls inside the window, end->data to currSum and subtract the value of the node that falls outside the window, start->data from currSum.
- currSum += end -> data – start -> data.
- Increment start and end to move the window over by one node (start = start->next and end = end->next).
- Update maxSum to be maximum of maxSum and currSum.
- Return maxSum.
Below is the code for the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
Node( int x)
{
data = x;
next = NULL;
}
};
int maxSubarraySum(Node* head, int k)
{
int maxSum = 0;
int currSum = 0;
Node* start = head;
Node* end = head;
for ( int i = 0; i < k && end != NULL; i++) {
currSum += end->data;
end = end->next;
}
maxSum = currSum;
while (end != NULL) {
currSum += end->data - start->data;
start = start->next;
end = end->next;
maxSum = max(maxSum, currSum);
}
return maxSum;
}
int main()
{
Node* head = new Node(1);
head->next = new Node(-2);
head->next->next = new Node(3);
head->next->next->next = new Node(4);
head->next->next->next->next = new Node(-1);
head->next->next->next->next->next = new Node(2);
int k = 3;
int maxSum = maxSubarraySum(head, k);
cout << "Maximum sum of a subarray of length " << k
<< " is: " << maxSum << endl;
return 0;
}
|
Java
import java.util.*;
class Node {
int data;
Node next;
Node( int x)
{
data = x;
next = null ;
}
}
class GFG {
public static int maxSubarraySum(Node head, int k)
{
int maxSum = 0 ;
int currSum = 0 ;
Node start = head;
Node end = head;
for ( int i = 0 ; i < k && end != null ; i++) {
currSum += end.data;
end = end.next;
}
maxSum = currSum;
while (end != null ) {
currSum += end.data - start.data;
start = start.next;
end = end.next;
maxSum = Math.max(maxSum, currSum);
}
return maxSum;
}
public static void main(String[] args)
{
Node head = new Node( 1 );
head.next = new Node(- 2 );
head.next.next = new Node( 3 );
head.next.next.next = new Node( 4 );
head.next.next.next.next = new Node(- 1 );
head.next.next.next.next.next = new Node( 2 );
int k = 3 ;
int maxSum = maxSubarraySum(head, k);
System.out.println(
"Maximum sum of a subarray of length " + k
+ " is: " + maxSum);
}
}
|
Python3
class Node:
def __init__( self , x):
self .data = x
self . next = None
def maxSubarraySum(head, k):
maxSum = 0
currSum = 0
start = head
end = head
for i in range (k):
if end is None :
break
currSum + = end.data
end = end. next
maxSum = currSum
while end is not None :
currSum + = end.data - start.data
start = start. next
end = end. next
maxSum = max (maxSum, currSum)
return maxSum
if __name__ = = '__main__' :
head = Node( 1 )
head. next = Node( - 2 )
head. next . next = Node( 3 )
head. next . next . next = Node( 4 )
head. next . next . next . next = Node( - 1 )
head. next . next . next . next . next = Node( 2 )
k = 3
maxSum = maxSubarraySum(head, k)
print ( "Maximum sum of a subarray of length" , k,
"is:" , maxSum)
|
C#
using System;
public class Node {
public int data;
public Node next;
public Node( int x)
{
data = x;
next = null ;
}
}
public class GFG {
public static int maxSubarraySum(Node head, int k)
{
int maxSum = 0;
int currSum = 0;
Node start = head;
Node end = head;
for ( int i = 0; i < k && end != null ; i++) {
currSum += end.data;
end = end.next;
}
maxSum = currSum;
while (end != null ) {
currSum += end.data - start.data;
start = start.next;
end = end.next;
maxSum = Math.Max(maxSum, currSum);
}
return maxSum;
}
static public void Main()
{
Node head = new Node(1);
head.next = new Node(-2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(-1);
head.next.next.next.next.next = new Node(2);
int k = 3;
int maxSum = maxSubarraySum(head, k);
Console.WriteLine(
"Maximum sum of a subarray of length " + k
+ " is: " + maxSum);
}
}
|
Javascript
class Node {
constructor(x) {
this .data = x;
this .next = null ;
}
}
function maxSubarraySum(head, k) {
let maxSum = 0;
let currSum = 0;
let start = head;
let end = head;
for (let i = 0; i < k && end !== null ; i++) {
currSum += end.data;
end = end.next;
}
maxSum = currSum;
while (end !== null ) {
currSum += end.data - start.data;
start = start.next;
end = end.next;
maxSum = Math.max(maxSum, currSum);
}
return maxSum;
}
( function main() {
const head = new Node(1);
head.next = new Node(-2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(-1);
head.next.next.next.next.next = new Node(2);
const k = 3;
const maxSum = maxSubarraySum(head, k);
console.log(
"Maximum sum of a subarray of length " + k
+ " is: " + maxSum);
})();
|
Output
Maximum sum of a subarray of length 3 is: 6
Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(1), as we are only using a constant amount of extra space to store the variables.
Approach 3: Prefix Sum
The prefix sum approach to find the maximum sum of a subarray of length K in a linked list involves the computing prefix sum of the linked list, and then finding the maximum sum of subarray of length K by using the formula sum[i]-sum[i-k], where the sum[i] is called ass the prefix sum up to index i.
Below are the steps for the above approach:
- Define the structure for the node in the linked list with two fields as data and next.
- Define a function called maxSubarraySum that takes two parameters, pointer to head of the liked list and an integer k, and returns an integer.
- Initialize a variable called maxSum to the minimum integer value.
- Initialize a variable called currSum to 0.
- Create a vector called prefixSum with size equal to the length of the linked list plus one.
- Set the first element of prefixSum to 0.
- Loop through the linked list and fill in the prefix sum values in the vector. For each node, add the node’s data to the previous prefix sum value and store the result in the current prefix sum value.
- Loop through the prefixSum vector and calculate the maximum subarray sum of length k using a sliding window approach. For each index i from k to the end of the vector, subtract the prefix sum value at i-k from the prefix sum value at i to get the sum of the subarray starting at i-k and ending at i. If this sum is greater than maxSum, update maxSum.
- Return maxSum.
- Implement the main function to create a linked list and call the maxSubarraySum function with appropriate parameters.
- Print the result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
Node( int x)
{
data = x;
next = NULL;
}
};
int maxSubarraySum(Node* head, int k)
{
vector< int > prefixSum;
prefixSum.push_back(0);
int sum = 0;
for (Node* curr = head; curr != NULL; curr = curr->next) {
sum += curr->data;
prefixSum.push_back(sum);
}
int maxSum = INT_MIN;
for ( int i = k; i < prefixSum.size(); i++) {
maxSum = max(maxSum, prefixSum[i] - prefixSum[i - k]);
}
return maxSum;
}
int main()
{
Node* head = new Node(1);
head->next = new Node(-2);
head->next->next = new Node(3);
head->next->next->next = new Node(4);
head->next->next->next->next = new Node(-1);
head->next->next->next->next->next = new Node(2);
int k = 3;
int maxSum = maxSubarraySum(head, k);
cout << "Maximum sum of a subarray of length " << k
<< " is: " << maxSum << endl;
return 0;
}
|
Java
import java.util.ArrayList;
class Node {
int data;
Node next;
Node( int x) {
data = x;
next = null ;
}
}
public class GFG {
static int maxSubarraySum(Node head, int k) {
ArrayList<Integer> prefixSum = new ArrayList<>();
prefixSum.add( 0 );
int sum = 0 ;
Node curr = head;
while (curr != null ) {
sum += curr.data;
prefixSum.add(sum);
curr = curr.next;
}
int maxSum = Integer.MIN_VALUE;
for ( int i = k; i < prefixSum.size(); i++) {
maxSum = Math.max(maxSum, prefixSum.get(i) - prefixSum.get(i - k));
}
return maxSum;
}
public static void main(String[] args) {
Node head = new Node( 1 );
head.next = new Node(- 2 );
head.next.next = new Node( 3 );
head.next.next.next = new Node( 4 );
head.next.next.next.next = new Node(- 1 );
head.next.next.next.next.next = new Node( 2 );
int k = 3 ;
int maxSum = maxSubarraySum(head, k);
System.out.println( "Maximum sum of a subarray of length " + k + " is: " + maxSum);
}
}
|
Python3
class Node:
def __init__( self , x):
self .data = x
self . next = None
def maxSubarraySum(head, k):
prefixSum = [ 0 ]
sum = 0
curr = head
while curr is not None :
sum + = curr.data
prefixSum.append( sum )
curr = curr. next
maxSum = float ( '-inf' )
for i in range (k, len (prefixSum)):
maxSum = max (maxSum, prefixSum[i] - prefixSum[i - k])
return maxSum
if __name__ = = "__main__" :
head = Node( 1 )
head. next = Node( - 2 )
head. next . next = Node( 3 )
head. next . next . next = Node( 4 )
head. next . next . next . next = Node( - 1 )
head. next . next . next . next . next = Node( 2 )
k = 3
maxSum = maxSubarraySum(head, k)
print ( "Maximum sum of a subarray of length" , k, "is:" , maxSum)
|
C#
using System;
using System.Collections.Generic;
public class Node
{
public int data;
public Node next;
public Node( int x)
{
data = x;
next = null ;
}
}
public class Program
{
public static int maxSubarraySum(Node head, int k)
{
List< int > prefixSum = new List< int >();
prefixSum.Add(0);
int sum = 0;
for (Node curr = head; curr != null ; curr = curr.next)
{
sum += curr.data;
prefixSum.Add(sum);
}
int maxSum = int .MinValue;
for ( int i = k; i < prefixSum.Count; i++)
{
maxSum = Math.Max(maxSum, prefixSum[i] - prefixSum[i - k]);
}
return maxSum;
}
public static void Main()
{
Node head = new Node(1);
head.next = new Node(-2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(-1);
head.next.next.next.next.next = new Node(2);
int k = 3;
int maxSum = maxSubarraySum(head, k);
Console.WriteLine( "Maximum sum of a subarray of length " + k + " is: " + maxSum);
}
}
|
Javascript
class Node {
constructor(x) {
this .data = x;
this .next = null ;
}
}
function maxSubarraySum(head, k) {
let prefixSum = [0];
let sum = 0;
let curr = head;
while (curr !== null ) {
sum += curr.data;
prefixSum.push(sum);
curr = curr.next;
}
let maxSum = Number.MIN_SAFE_INTEGER;
for (let i = k; i < prefixSum.length; i++) {
maxSum = Math.max(maxSum, prefixSum[i] - prefixSum[i - k]);
}
return maxSum;
}
let head = new Node(1);
head.next = new Node(-2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(-1);
head.next.next.next.next.next = new Node(2);
let k = 3;
let maxSum = maxSubarraySum(head, k);
console.log( "Maximum sum of a subarray of length " + k + ": " + maxSum);
|
Output
Maximum sum of a subarray of length 3 is: 6
Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(n), where n is the number of nodes in the linked list, because we are creating an array to store the prefix sum of the linked list nodes.
Related Articles:
Last Updated :
14 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...