Find the Max product Sublist of length K in a Linked list
Last Updated :
07 Nov, 2023
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++
#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;
}
};
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;
cout << sol.maxProduct(head, k) << endl;
return 0;
}
|
Java
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;
}
}
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 ;
System.out.println(sol.maxProduct(head, k));
}
}
|
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
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
print (sol.maxProduct(head, k))
|
C#
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 {
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;
Console.WriteLine(sol.MaxProduct(head, k));
}
}
|
Javascript
class Node {
constructor(val) {
this .val = val;
this .next = null ;
}
}
class Solution {
maxProduct(head, k) {
const arr = [];
let curr = head;
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;
for (let i = 0; i < k; i++) {
prod *= arr[i];
}
maxProd = Math.max(maxProd, prod);
while (right < n - 1) {
prod /= arr[left];
prod *= arr[right + 1];
left++;
right++;
maxProd = Math.max(maxProd, prod);
}
return maxProd;
}
}
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;
console.log(sol.maxProduct(head, k));
|
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++
#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;
}
};
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;
cout << sol.maxProduct(head, k) << endl;
return 0;
}
|
Java
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;
}
}
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 ;
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
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
print (sol.maxProduct(head, k))
|
C#
using System;
using System.Collections.Generic;
public class Node
{
public int Val { get ; set ; }
public Node Next { get ; set ; }
public Node( int x)
{
Val = x;
Next = null ;
}
}
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;
Console.WriteLine(sol.MaxProduct(head, k));
}
}
|
Javascript
<script>
class Node {
constructor(x) {
this .val = x;
this .next = null ;
}
}
class Solution {
maxProduct(head, k) {
let max_prod = 0;
let prod = 1;
let count = 0;
let curr = head;
let q = [];
while (curr !== null ) {
q.push(curr.val);
count++;
prod *= curr.val;
if (count > k) {
let front = q.shift();
prod /= front;
count--;
}
if (count === k) {
max_prod = Math.max(max_prod, prod);
}
curr = curr.next;
}
return max_prod;
}
}
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(5);
let sol = new Solution();
let k = 3;
document.write(sol.maxProduct(head, k));
</script>
|
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.
Share your thoughts in the comments
Please Login to comment...