Open In App

Find the Max product Sublist of length K in a Linked list

Last Updated : 07 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a linked list of integers and a number K, find the maximum product of a sublist of length K in a linked list.

Examples:

Input: List: 1 -> -2 -> -3 -> 4 -> -5, K = 3
Output: 60
Explanation: The product of sublist -3 -> 4 -> -5 is 60 which is the maximum product of a sublist of length K = 3.

Input: List: 2 -> 4 -> 6 -> 8 -> 10, K = 2
Output: 80
Explanation: The product of sublist 8 -> 10 is 80 which is the maximum product of a sublist of length K = 2.

Approach: To solve the problem using the Sliding window approach follow the below idea:

Traverse the linked list and stores the values in a vector. Then it initializes the left and right indices of the sliding window, calculates the product of the first sublist of size K, and sets it as the maximum product seen so far. It then slides the window to the right, updates the product, and checks if it is greater than the current maximum product. Finally, it returns the maximum product. 

Below are the steps for the above approach:

  • Traverse the linked list and store the values in a vector.
  • Initialize the left and right indices of the sliding window to the first K-1 elements of the vector.
  • Compute the product of the first sublist of size K by iterating over the first K elements of the vector.
  • Set the maximum product seen so far to the product computed in step 3.
  • Slide the window to the right by incrementing both the left and right indices by 1.
  • Update the product by dividing it by the first element in the previous sublist and multiplying it by the next element in the vector.
  • Check if the product is greater than the maximum product seen so far and update the maximum product if necessary.
  • Return the maximum product.

Below is the code for the above approach:

C++




// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
 
struct Node {
    int val;
    Node* next;
    Node(int x)
        : val(x), next(NULL)
    {
    }
};
 
class Solution {
public:
    int maxProduct(Node* head, int k)
    {
        vector<int> arr;
        Node* curr = head;
        while (curr != NULL) {
            arr.push_back(curr->val);
            curr = curr->next;
        }
        int n = arr.size();
        int left = 0, right = k - 1;
        int prod = 1, max_prod = 0;
        for (int i = 0; i < k; i++) {
            prod *= arr[i];
        }
        max_prod = max(max_prod, prod);
        while (right < n - 1) {
            prod /= arr[left];
            prod *= arr[right + 1];
            left++;
            right++;
            max_prod = max(max_prod, prod);
        }
        return max_prod;
    }
};
 
// Drivers code
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(5);
    Solution sol;
    int k = 3;
 
    // Function Call
    cout << sol.maxProduct(head, k) << endl;
    return 0;
}


Java




// Java code for the above approach
import java.util.*;
 
class Node {
    int val;
    Node next;
 
    public Node(int x)
    {
        val = x;
        next = null;
    }
}
 
class Solution {
    public int maxProduct(Node head, int k)
    {
        List<Integer> arr = new ArrayList<>();
        Node curr = head;
        while (curr != null) {
            arr.add(curr.val);
            curr = curr.next;
        }
        int n = arr.size();
        int left = 0, right = k - 1;
        int prod = 1, max_prod = 0;
        for (int i = 0; i < k; i++) {
            prod *= arr.get(i);
        }
        max_prod = Math.max(max_prod, prod);
        while (right < n - 1) {
            prod /= arr.get(left);
            prod *= arr.get(right + 1);
            left++;
            right++;
            max_prod = Math.max(max_prod, prod);
        }
        return max_prod;
    }
}
 
// Driver code
public class Main {
    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(5);
        Solution sol = new Solution();
        int k = 3;
 
        // Function Call
        System.out.println(sol.maxProduct(head, k));
    }
}
 
// This code is contributed by Prajwal Kandekar


Python3




class Node:
    def __init__(self, x):
        self.val = x
        self.next = None
 
class Solution:
    def maxProduct(self, head, k):
        arr = []
        curr = head
        while curr is not None:
            arr.append(curr.val)
            curr = curr.next
        n = len(arr)
        left = 0
        right = k - 1
        prod = 1
        max_prod = 0
        for i in range(k):
            prod *= arr[i]
        max_prod = max(max_prod, prod)
        while right < n - 1:
            prod //= arr[left]
            prod *= arr[right + 1]
            left += 1
            right += 1
            max_prod = max(max_prod, prod)
        return max_prod
 
# Driver code
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(5)
    sol = Solution()
    k = 3
 
    # Function call
    print(sol.maxProduct(head, k))


C#




// C# code for the above approach
using System;
using System.Collections.Generic;
 
public class Node {
    public int val;
    public Node next;
 
    public Node(int x)
    {
        val = x;
        next = null;
    }
}
 
public class Solution {
    public int MaxProduct(Node head, int k)
    {
        List<int> arr = new List<int>();
        Node curr = head;
        while (curr != null) {
            arr.Add(curr.val);
            curr = curr.next;
        }
        int n = arr.Count;
        int left = 0, right = k - 1;
        int prod = 1, max_prod = 0;
        for (int i = 0; i < k; i++) {
            prod *= arr[i];
        }
        max_prod = Math.Max(max_prod, prod);
        while (right < n - 1) {
            prod /= arr[left];
            prod *= arr[right + 1];
            left++;
            right++;
            max_prod = Math.Max(max_prod, prod);
        }
        return max_prod;
    }
}
 
public class GFG {
    // Drive code
    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(5);
        Solution sol = new Solution();
        int k = 3;
 
        // Function Call
        Console.WriteLine(sol.MaxProduct(head, k));
    }
}


Javascript




// Define a class to represent a node in the linked list
class Node {
    constructor(val) {
        this.val = val;   // Value stored in the node
        this.next = null; // Reference to the next node (initially null)
    }
}
 
// Define a class for the solution
class Solution {
    maxProduct(head, k) {
        const arr = []; // Create an array to store the linked list values
        let curr = head; // Start at the head of the linked list
 
        // Traverse the linked list and store values in the array
        while (curr !== null) {
            arr.push(curr.val);
            curr = curr.next;
        }
 
        const n = arr.length;
        let left = 0;
        let right = k - 1;
        let prod = 1;
        let maxProd = 0;
 
        // Calculate the initial product of the first 'k' elements
        for (let i = 0; i < k; i++) {
            prod *= arr[i];
        }
 
        // Update the maximum product if the initial product is greater
        maxProd = Math.max(maxProd, prod);
 
        // Sliding window approach to find the maximum product
        while (right < n - 1) {
            // Divide by the element going out of the window and multiply by the new element
            prod /= arr[left];
            prod *= arr[right + 1];
            left++; // Move the left pointer
            right++; // Move the right pointer
            // Update the maximum product if a greater product is found
            maxProd = Math.max(maxProd, prod);
        }
 
        return maxProd; // Return the maximum product
    }
}
 
// Driver code
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(5);
 
const sol = new Solution();
const k = 3;
 
// Function Call to find the maximum product of 'k' consecutive elements
console.log(sol.maxProduct(head, k));


Output

60












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. This is because we are storing the values of the linked list in a vector.

Approach 2 : 

The given code provided finds the largest product of k consecutive nodes in a linked list using a sliding window method. The answer makes use of a queue to store the values of the latest k nodes, and a variable called prod to store the sum of all the nodes in the queue. When the queue size surpasses k, the queue is updated by pushing the values of the most recent node and popping the oldest value. The product is calculated at each step by multiplying all the values in the queue, and if required, the maximum product observed thus far is updated.
 

Below are the steps for the above approach:

  • Create a vector arr and a pointer curr to the head of the linked list.
  • Iterate through the linked list and append each node’s value to the vector.
  • Initialize variables left and right to 0 and k-1, respectively. Compute the product prod of the first k values in the vector, and initialize max_prod to prod.
  • Slide the window to the right by moving left and right to the right by 1 position at each iteration. At each iteration, update the product prod by dividing by the value at left and multiplying by the value at right+1.
  • Update max_prod if prod is greater than the current value of max_prod.
  • Repeat step 4 and 5 until the right endpoint of the window reaches the end of the vector.
  • Return max_prod.

C++




// c++ code implementation for above approach
#include <bits/stdc++.h>
using namespace std;
 
struct Node {
    int val;
    Node* next;
    Node(int x) : val(x), next(NULL) {}
};
 
class Solution {
public:
    int maxProduct(Node* head, int k) {
        int max_prod = 0;
        int prod = 1;
        int count = 0;
        Node* curr = head;
        queue<int> q;
        while (curr != NULL) {
            q.push(curr->val);
            count++;
            prod *= curr->val;
            if (count > k) {
                int front = q.front();
                q.pop();
                prod /= front;
                count--;
            }
            if (count == k) {
                max_prod = max(max_prod, prod);
            }
            curr = curr->next;
        }
        return max_prod;
    }
};
 
// Drive code
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(5);
    Solution sol;
    int k = 3;
    // Function call
    cout << sol.maxProduct(head, k) << endl;
    return 0;
}


Java




/*package whatever //do not write package name here */
 
import java.util.LinkedList;
import java.util.Queue;
 
class Node {
    int val;
    Node next;
 
    Node(int x) {
        val = x;
        next = null;
    }
}
 
class Solution {
    public int maxProduct(Node head, int k) {
        int max_prod = 0;
        int prod = 1;
        int count = 0;
        Node curr = head;
        Queue<Integer> q = new LinkedList<>();
 
        while (curr != null) {
            q.add(curr.val);
            count++;
            prod *= curr.val;
 
            if (count > k) {
                int front = q.poll();
                prod /= front;
                count--;
            }
 
            if (count == k) {
                max_prod = Math.max(max_prod, prod);
            }
 
            curr = curr.next;
        }
 
        return max_prod;
    }
}
 
// Drive code
public class Main {
    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(5);
        Solution sol = new Solution();
        int k = 3;
        // Function call
        System.out.println(sol.maxProduct(head, k));
    }
}


Python3




from queue import Queue
 
class Node:
    def __init__(self, x):
        self.val = x
        self.next = None
 
class Solution:
    def maxProduct(self, head, k):
        max_prod = 0
        prod = 1
        count = 0
        curr = head
        q = Queue()
        while curr is not None:
            q.put(curr.val)
            count += 1
            prod *= curr.val
            if count > k:
                front = q.get()
                prod //= front
                count -= 1
            if count == k:
                max_prod = max(max_prod, prod)
            curr = curr.next
        return max_prod
 
# Driver code
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)
head.next.next.next.next = Node(5)
sol = Solution()
k = 3
# Function call
print(sol.maxProduct(head, k))


C#




using System;
using System.Collections.Generic;
 
// Define a Node class for the linked list
public class Node
{
    public int Val { get; set; }
    public Node Next { get; set; }
 
    public Node(int x)
    {
        Val = x;
        Next = null;
    }
}
 
// Define the Solution class
public class Solution
{
    public int MaxProduct(Node head, int k)
    {
        int maxProd = 0;
        int prod = 1;
        int count = 0;
        Node curr = head;
        Queue<int> queue = new Queue<int>();
 
        while (curr != null)
        {
            queue.Enqueue(curr.Val);
            count++;
            prod *= curr.Val;
 
            if (count > k)
            {
                int front = queue.Dequeue();
                prod /= front;
                count--;
            }
 
            if (count == k)
            {
                maxProd = Math.Max(maxProd, prod);
            }
 
            curr = curr.Next;
        }
 
        return maxProd;
    }
}
 
class Program
{
    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(5);
 
        Solution sol = new Solution();
        int k = 3;
 
        // Function call
        Console.WriteLine(sol.MaxProduct(head, k));
    }
}


Javascript




<script>
// JavaScript code for the above approach
 
// Definition of a Node for the linked list
class Node {
    constructor(x) {
        this.val = x; // Value of the node
        this.next = null; // Pointer to the next node
    }
}
 
// Class to implement the solution
class Solution {
    // Function to find the maximum product of K consecutive nodes
    maxProduct(head, k) {
        let max_prod = 0; // Variable to store the maximum product found
        let prod = 1; // Variable to keep track of the current product
        let count = 0; // Variable to keep track of the number of nodes encountered
        let curr = head; // Pointer to traverse the linked list
        let q = []; // Queue to keep track of the last K values encountered
 
        // Traverse the linked list
        while (curr !== null) {
            q.push(curr.val); // Push the current node's value to the queue
            count++; // Increment the count of nodes encountered
            prod *= curr.val; // Update the product
 
            // If the count exceeds K, update the product and count accordingly
            if (count > k) {
                let front = q.shift(); // Remove the first element from the queue
                prod /= front; // Adjust the product
                count--; // Decrement the count
            }
 
            // If K nodes have been encountered, update the maximum product
            if (count === k) {
                max_prod = Math.max(max_prod, prod); // Update the maximum product if necessary
            }
 
            curr = curr.next; // Move to the next node
        }
        return max_prod; // Return the maximum product found
    }
}
 
// Driver code
let head = new Node(1); // Create the first node
head.next = new Node(2); // Add the second node
head.next.next = new Node(3); // Add the third node
head.next.next.next = new Node(4); // Add the fourth node
head.next.next.next.next = new Node(5); // Add the fifth node
 
let sol = new Solution(); // Create an instance of the solution class
let k = 3; // Set the value of K
 
// Function call to find the maximum product of K consecutive nodes
document.write(sol.maxProduct(head, k)); // Print the result
 
// This code is contributed by Susobhan Akhuli
</script>


Output

60












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. 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads