Open In App

Find the Max sum of Subarray of length K in a Linked List

Improve
Improve
Like Article
Like
Save
Share
Report

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++




// 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




// 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);
    }
}


Python3




# 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#




// 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




// 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:

  • 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++




//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;
}


Java




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


Python3




# 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)


C#




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);
    }
}


Javascript




// 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:



Last Updated : 14 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads