Open In App

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:

Below is the code for the above approach:




// C++ code of above approach
#include <bits/stdc++.h>
using namespace std;
 
// Define the structure of a
// node in the linked list
struct Node {
    int data;
    struct Node* next;
    Node(int x)
    {
        data = x;
        next = NULL;
    }
};
 
// Function to Finding Maximum Sum of
// Subarray of Length K in a Linked List
// Using Sliding window Algorithm
int maxSubarraySum(Node* head, int k)
{
 
    // Variables for storing current
    // and maximum sum
    int maxSum = 0;
    int currSum = 0;
 
    // Initialize the sliding window
    // with two pointers
    Node* start = head;
    Node* end = head;
 
    // Compute the sum of the
    // first k elements
    for (int i = 0; i < k && end != NULL; i++) {
        currSum += end->data;
        end = end->next;
    }
 
    maxSum = currSum;
 
    // Slide the window over
    // the linked list
    while (end != NULL) {
        currSum += end->data - start->data;
        start = start->next;
        end = end->next;
 
        // Update maxSum to be the maximum
        // of maxSum and currSum.
        maxSum = max(maxSum, currSum);
    }
 
    // Return the maximum sum
    return maxSum;
}
 
// Driver code
int main()
{
 
    // Create a linked list:
    // 1 -> -2 -> 3 -> 4 -> -1 -> 2
    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);
 
    // Find the maximum sum of a
    // subarray of length 3.
    int k = 3;
 
    // Function Call
    int maxSum = maxSubarraySum(head, k);
 
    cout << "Maximum sum of a subarray of length " << k
         << " is: " << maxSum << endl;
 
    return 0;
}




// Java code of above approach
 
import java.util.*;
 
// Define the structure of a
// node in the linked list
class Node {
    int data;
    Node next;
 
    Node(int x)
    {
        data = x;
        next = null;
    }
}
 
class GFG {
    // Function to Finding Maximum Sum of
    // Subarray of Length K in a Linked List
    // Using Sliding window Algorithm
    public static int maxSubarraySum(Node head, int k)
    {
        // Variables for storing current
        // and maximum sum
        int maxSum = 0;
        int currSum = 0;
 
        // Initialize the sliding window
        // with two pointers
        Node start = head;
        Node end = head;
 
        // Compute the sum of the
        // first k elements
        for (int i = 0; i < k && end != null; i++) {
            currSum += end.data;
            end = end.next;
        }
 
        maxSum = currSum;
 
        // Slide the window over
        // the linked list
        while (end != null) {
            currSum += end.data - start.data;
            start = start.next;
            end = end.next;
 
            // Update maxSum to be the maximum
            // of maxSum and currSum.
            maxSum = Math.max(maxSum, currSum);
        }
 
        // Return the maximum sum
        return maxSum;
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        // Create a linked list:
        // 1 -> -2 -> 3 -> 4 -> -1 -> 2
        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);
 
        // Find the maximum sum of a
        // subarray of length 3.
        int k = 3;
 
        // Function Call
        int maxSum = maxSubarraySum(head, k);
 
        System.out.println(
            "Maximum sum of a subarray of length " + k
            + " is: " + maxSum);
    }
}




# Define the structure of a
# node in the linked list
 
 
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None
 
# Function to Finding Maximum Sum of
# Subarray of Length K in a Linked List
# Using Sliding window Algorithm
 
 
def maxSubarraySum(head, k):
 
    # Variables for storing current
    # and maximum sum
    maxSum = 0
    currSum = 0
 
    # Initialize the sliding window
    # with two pointers
    start = head
    end = head
 
    # Compute the sum of the
    # first k elements
    for i in range(k):
        if end is None:
            break
        currSum += end.data
        end = end.next
 
    maxSum = currSum
 
    # Slide the window over
    # the linked list
    while end is not None:
        currSum += end.data - start.data
        start = start.next
        end = end.next
 
        # Update maxSum to be the maximum
        # of maxSum and currSum.
        maxSum = max(maxSum, currSum)
 
    # Return the maximum sum
    return maxSum
 
 
# Driver code
if __name__ == '__main__':
 
    # Create a linked list:
    # 1 -> -2 -> 3 -> 4 -> -1 -> 2
    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)
 
    # Find the maximum sum of a
    # subarray of length 3.
    k = 3
 
    # Function Call
    maxSum = maxSubarraySum(head, k)
 
    print("Maximum sum of a subarray of length", k,
          "is:", maxSum)
 
# This code is contributed by Susobhan Akhuli




// C# code for the above approach:
 
using System;
 
// Define the structure of a node in the linked list
public class Node {
    public int data;
    public Node next;
 
    public Node(int x)
    {
        data = x;
        next = null;
    }
}
 
public class GFG {
 
    // Function to Finding Maximum Sum of Subarray of Length
    // K in a Linked List Using Sliding window Algorithm
    public static int maxSubarraySum(Node head, int k)
    {
        // Variables for storing current and maximum sum
        int maxSum = 0;
        int currSum = 0;
 
        // Initialize the sliding window with two pointers
        Node start = head;
        Node end = head;
 
        // Compute the sum of the first k elements
        for (int i = 0; i < k && end != null; i++) {
            currSum += end.data;
            end = end.next;
        }
 
        maxSum = currSum;
 
        // Slide the window over the linked list
        while (end != null) {
            currSum += end.data - start.data;
            start = start.next;
            end = end.next;
 
            // Update maxSum to be the maximum of maxSum and
            // currSum.
            maxSum = Math.Max(maxSum, currSum);
        }
 
        // Return the maximum sum
        return maxSum;
    }
 
    static public void Main()
    {
 
        // Code
        // Create a linked list:
        // 1 -> -2 -> 3 -> 4 -> -1 -> 2
        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);
 
        // Find the maximum sum of a subarray of length 3.
        int k = 3;
 
        // Function Call
        int maxSum = maxSubarraySum(head, k);
 
        Console.WriteLine(
            "Maximum sum of a subarray of length " + k
            + " is: " + maxSum);
    }
}
 
// This code is contributed by karthik.




// JavaScript code of above approach
 
// Define the structure of a
// node in the linked list
class Node {
constructor(x) {
this.data = x;
this.next = null;
}
}
 
// Function to Finding Maximum Sum of
// Subarray of Length K in a Linked List
// Using Sliding window Algorithm
function maxSubarraySum(head, k) {
// Variables for storing current
// and maximum sum
let maxSum = 0;
let currSum = 0;
 
// Initialize the sliding window
// with two pointers
let start = head;
let end = head;
 
// Compute the sum of the
// first k elements
for (let i = 0; i < k && end !== null; i++) {
currSum += end.data;
end = end.next;
}
 
maxSum = currSum;
 
// Slide the window over
// the linked list
while (end !== null) {
currSum += end.data - start.data;
start = start.next;
end = end.next;
 
// Update maxSum to be the maximum
// of maxSum and currSum.
maxSum = Math.max(maxSum, currSum);
}
 
// Return the maximum sum
return maxSum;
}
 
// Driver code
(function main() {
// Create a linked list:
// 1 -> -2 -> 3 -> 4 -> -1 -> 2
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);
 
// Find the maximum sum of a
// subarray of length 3.
const k = 3;
 
// Function Call
const maxSum = maxSubarraySum(head, k);
 
console.log(
"Maximum sum of a subarray of length " + k
+ " is: " + maxSum);
})();
 
// This code is contributed by Susobhan Akhuli.

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:

Below is the implementation of the above approach:




//C++ code for the abpve approach
#include <bits/stdc++.h>
using namespace std;
 
// Define the structure of a
// node in the linked list
struct Node {
    int data;
    struct Node* next;
    Node(int x)
    {
        data = x;
        next = NULL;
    }
};
 
// Function to Finding Maximum Sum of
// Subarray of Length K in a Linked List
// Using Prefix Sum Algorithm
int maxSubarraySum(Node* head, int k)
{
    // Compute the prefix sum of the
    // linked list data
    vector<int> prefixSum;
    prefixSum.push_back(0); // Add an initial 0
    int sum = 0;
    for (Node* curr = head; curr != NULL; curr = curr->next) {
        sum += curr->data;
        prefixSum.push_back(sum);
    }
 
    // Compute the maximum sum using
    // the prefix sum array
    int maxSum = INT_MIN;
    for (int i = k; i < prefixSum.size(); i++) {
        maxSum = max(maxSum, prefixSum[i] - prefixSum[i - k]);
    }
 
    // Return the maximum sum
    return maxSum;
}
 
// Driver code
int main()
{
    // Create a linked list:
    // 1 -> -2 -> 3 -> 4 -> -1 -> 2
    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);
 
    // Find the maximum sum of a
    // subarray of length 3.
    int k = 3;
 
    // Function Call
    int maxSum = maxSubarraySum(head, k);
 
    cout << "Maximum sum of a subarray of length " << k
         << " is: " << maxSum << endl;
 
    return 0;
}




import java.util.ArrayList;
 
// Define the structure of a
// node in the linked list
class Node {
    int data;
    Node next;
 
    Node(int x) {
        data = x;
        next = null;
    }
}
 
public class GFG {
    // Function to Finding Maximum Sum of
    // Subarray of Length K in a Linked List
    // Using Prefix Sum Algorithm
    static int maxSubarraySum(Node head, int k) {
        // Compute the prefix sum of the
        // linked list data
        ArrayList<Integer> prefixSum = new ArrayList<>();
        prefixSum.add(0); // Add an initial 0
        int sum = 0;
        Node curr = head;
        while (curr != null) {
            sum += curr.data;
            prefixSum.add(sum);
            curr = curr.next;
        }
 
        // Compute the maximum sum using
        // the prefix sum array
        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 the maximum sum
        return maxSum;
    }
 
    // Driver code
    public static void main(String[] args) {
        // Create a linked list:
        // 1 -> -2 -> 3 -> 4 -> -1 -> 2
        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);
 
        // Find the maximum sum of a
        // subarray of length 3.
        int k = 3;
 
        // Function Call
        int maxSum = maxSubarraySum(head, k);
 
        System.out.println("Maximum sum of a subarray of length " + k + " is: " + maxSum);
    }
}
// Contributed by Aditi Tyagi




# Define the structure of a
# node in the linked list
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None
 
# Function to Finding Maximum Sum of
# Subarray of Length K in a Linked List
# Using Prefix Sum Algorithm
def maxSubarraySum(head, k):
    # Compute the prefix sum of the
    # linked list data
    prefixSum = [0# Add an initial 0
    sum = 0
    curr = head
    while curr is not None:
        sum += curr.data
        prefixSum.append(sum)
        curr = curr.next
 
    # Compute the maximum sum using
    # the prefix sum array
    maxSum = float('-inf')
    for i in range(k, len(prefixSum)):
        maxSum = max(maxSum, prefixSum[i] - prefixSum[i - k])
 
    # Return the maximum sum
    return maxSum
 
# Driver code
if __name__ == "__main__":
    # Create a linked list:
    # 1 -> -2 -> 3 -> 4 -> -1 -> 2
    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)
 
    # Find the maximum sum of a
    # subarray of length 3.
    k = 3
 
    # Function Call
    maxSum = maxSubarraySum(head, k)
 
    print("Maximum sum of a subarray of length", k, "is:", maxSum)




using System;
using System.Collections.Generic;
 
// Define the structure of a
// node in the linked list
public class Node
{
    public int data;
    public Node next;
    public Node(int x)
    {
        data = x;
        next = null;
    }
}
 
public class Program
{
   
      // Function to Finding Maximum Sum of
    // Subarray of Length K in a Linked List
    // Using Prefix Sum Algorithm
    public static int maxSubarraySum(Node head, int k)
    {
       
          // Compute the prefix sum of the
        // linked list data
        List<int> prefixSum = new List<int>();
       
          // Add an initial 0
        prefixSum.Add(0);
        int sum = 0;
        for (Node curr = head; curr != null; curr = curr.next)
        {
            sum += curr.data;
            prefixSum.Add(sum);
        }
 
          // Compute the maximum sum using
            // the prefix sum array
        int maxSum = int.MinValue;
        for (int i = k; i < prefixSum.Count; i++)
        {
            maxSum = Math.Max(maxSum, prefixSum[i] - prefixSum[i - k]);
        }
 
          // Return the maximum sum
        return maxSum;
    }
 
      // Driver code
    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);
    }
}




// Define the structure of a
// node in the linked list
class Node {
    constructor(x) {
        this.data = x;
        this.next = null;
    }
}
 
// Function to Finding Maximum Sum of
// Subarray of Length K in a Linked List
// Using Prefix Sum Algorithm
function maxSubarraySum(head, k) {
 
    // Compute the prefix sum of the
    // linked list data
    let prefixSum = [0];
    let sum = 0;
    let curr = head;
    while (curr !== null) {
        sum += curr.data;
        prefixSum.push(sum);
        curr = curr.next;
    }
     
    // Compute the maximum sum using
    // the prefix sum array
    let maxSum = Number.MIN_SAFE_INTEGER;
    for (let i = k; i < prefixSum.length; i++) {
        maxSum = Math.max(maxSum, prefixSum[i] - prefixSum[i - k]);
    }
     
    // Return the maximum sum
    return maxSum;
}
 
// Driver code
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);
 
// Find the maximum sum of a
// subarray of length 3.
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:


Article Tags :