Maximum sum contiguous nodes in the given linked list
Last Updated :
09 Jun, 2021
Given a linked list, the task is to find the maximum sum for any contiguous nodes.
Examples:
Input: -2 -> -3 -> 4 -> -1 -> -2 -> 1 -> 5 -> -3 -> NULL
Output: 7
4 -> -1 -> -2 -> 1 -> 5 is the sub-list with the given sum.
Input: 1 -> 2 -> 3 -> 4 -> NULL
Output: 10
Approach: Kadane's algorithm has been discussed in this article to work on arrays to find the maximum sub-array sum but it can be modified to work on linked lists too. Since Kadane's algorithm doesn't require to access random elements, it is also applicable on the linked lists in linear time.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// A linked list node
class Node {
public:
int data;
Node* next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, appends a new node at the end */
void append(Node** head_ref, int new_data)
{
// Allocate node
Node* new_node = new Node();
Node* last = *head_ref; /* used in step 5*/
// Put in the data
new_node->data = new_data;
/* This new node is going to be
the last node, so make next of
it as NULL*/
new_node->next = NULL;
/* If the Linked List is empty,
then make the new node as head */
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}
// Else traverse till the last node
while (last->next != NULL)
last = last->next;
// Change the next of last node
last->next = new_node;
return;
}
// Function to return the maximum contiguous
// nodes sum in the given linked list
int MaxContiguousNodeSum(Node* head)
{
// If the list is empty
if (head == NULL)
return 0;
// If the list contains a single element
if (head->next == NULL)
return head->data;
// max_ending_here will store the maximum sum
// ending at the current node, currently it
// will be initialised to the maximum sum ending
// at the first node which is the first node's value
int max_ending_here = head->data;
// max_so_far will store the maximum sum of
// contiguous nodes so far which is the required
// answer at the end of the linked list traversal
int max_so_far = head->data;
// Starting from the second node
head = head->next;
// While there are nodes in linked list
while (head != NULL) {
// max_ending_here will be the maximum of either
// the current node's value or the current node's
// value added with the max_ending_here
// for the previous node
max_ending_here = max(head->data,
max_ending_here + head->data);
// Update the maximum sum so far
max_so_far = max(max_ending_here, max_so_far);
// Get to the next node
head = head->next;
}
// Return the maximum sum so far
return max_so_far;
}
// Driver code
int main()
{
// Create the linked list
Node* head = NULL;
append(&head, -2);
append(&head, -3);
append(&head, 4);
append(&head, -1);
append(&head, -2);
append(&head, 1);
append(&head, 5);
append(&head, -3);
cout << MaxContiguousNodeSum(head);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// A linked list node
static class Node
{
int data;
Node next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, appends a new node at the end */
static Node append(Node head_ref, int new_data)
{
// Allocate node
Node new_node = new Node();
Node last = head_ref; /* used in step 5*/
// Put in the data
new_node.data = new_data;
/* This new node is going to be
the last node, so make next of
it as null*/
new_node.next = null;
/* If the Linked List is empty,
then make the new node as head */
if (head_ref == null)
{
head_ref = new_node;
return head_ref;
}
// Else traverse till the last node
while (last.next != null)
last = last.next;
// Change the next of last node
last.next = new_node;
return head_ref;
}
// Function to return the maximum contiguous
// nodes sum in the given linked list
static int MaxContiguousNodeSum(Node head)
{
// If the list is empty
if (head == null)
return 0;
// If the list contains a single element
if (head.next == null)
return head.data;
// max_ending_here will store the maximum sum
// ending at the current node, currently it
// will be initialised to the maximum sum ending
// at the first node which is the first node's value
int max_ending_here = head.data;
// max_so_far will store the maximum sum of
// contiguous nodes so far which is the required
// answer at the end of the linked list traversal
int max_so_far = head.data;
// Starting from the second node
head = head.next;
// While there are nodes in linked list
while (head != null)
{
// max_ending_here will be the maximum of either
// the current node's value or the current node's
// value added with the max_ending_here
// for the previous node
max_ending_here = Math.max(head.data,
max_ending_here + head.data);
// Update the maximum sum so far
max_so_far = Math.max(max_ending_here, max_so_far);
// Get to the next node
head = head.next;
}
// Return the maximum sum so far
return max_so_far;
}
// Driver code
public static void main(String[] args)
{
// Create the linked list
Node head = null;
head = append(head, -2);
head = append(head, -3);
head = append(head, 4);
head = append(head, -1);
head = append(head, -2);
head = append(head, 1);
head = append(head, 5);
head = append(head, -3);
System.out.print(MaxContiguousNodeSum(head));
}
}
// This code is contributed by PrinciRaj1992
Python3
# Python3 implementation of the approach
# A linked list node
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Given a reference (pointer to pointer)
# to the head of a list and an int,
# appends a new node at the end
def append(head_ref, new_data):
# Allocate node
new_node = Node(new_data)
last = head_ref # used in step 5
# This new node is going to be
# the last node, so make next of
# it as None
new_node.next = None
# If the Linked List is empty,
# then make the new node as head
if (head_ref == None):
head_ref = new_node
return head_ref
# Else traverse till the last node
while (last.next != None):
last = last.next
# Change the next of last node
last.next = new_node
return head_ref
# Function to return the maximum contiguous
# nodes sum in the given linked list
def MaxContiguousNodeSum(head):
# If the list is empty
if (head == None):
return 0
# If the list contains a single element
if (head.next == None):
return head.data
# max_ending_here will store the maximum
# sum ending at the current node, currently
# it will be initialised to the maximum
# sum ending at the first node which is
# the first node's value
max_ending_here = head.data
# max_so_far will store the maximum sum of
# contiguous nodes so far which is the required
# answer at the end of the linked list traversal
max_so_far = head.data
# Starting from the second node
head = head.next
# While there are nodes in linked list
while (head != None):
# max_ending_here will be the maximum of either
# the current node's value or the current node's
# value added with the max_ending_here
# for the previous node
max_ending_here = max(head.data,
max_ending_here +
head.data)
# Update the maximum sum so far
max_so_far = max(max_ending_here,
max_so_far)
# Get to the next node
head = head.next
# Return the maximum sum so far
return max_so_far
# Driver code
if __name__=='__main__':
# Create the linked list
head = None
head = append(head, -2)
head = append(head, -3)
head = append(head, 4)
head = append(head, -1)
head = append(head, -2)
head = append(head, 1)
head = append(head, 5)
head = append(head, -3)
print(MaxContiguousNodeSum(head))
# This code is contributed by rutvik_56
C#
// C# implementation of the approach
using System;
class GFG
{
// A linked list node
public class Node
{
public int data;
public Node next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, appends a new node at the end */
static Node append(Node head_ref, int new_data)
{
// Allocate node
Node new_node = new Node();
Node last = head_ref; /* used in step 5*/
// Put in the data
new_node.data = new_data;
/* This new node is going to be
the last node, so make next of
it as null*/
new_node.next = null;
/* If the Linked List is empty,
then make the new node as head */
if (head_ref == null)
{
head_ref = new_node;
return head_ref;
}
// Else traverse till the last node
while (last.next != null)
last = last.next;
// Change the next of last node
last.next = new_node;
return head_ref;
}
// Function to return the maximum contiguous
// nodes sum in the given linked list
static int MaxContiguousNodeSum(Node head)
{
// If the list is empty
if (head == null)
return 0;
// If the list contains a single element
if (head.next == null)
return head.data;
// max_ending_here will store the maximum sum
// ending at the current node, currently it
// will be initialised to the maximum sum ending
// at the first node which is the first node's value
int max_ending_here = head.data;
// max_so_far will store the maximum sum of
// contiguous nodes so far which is the required
// answer at the end of the linked list traversal
int max_so_far = head.data;
// Starting from the second node
head = head.next;
// While there are nodes in linked list
while (head != null)
{
// max_ending_here will be the maximum of either
// the current node's value or the current node's
// value added with the max_ending_here
// for the previous node
max_ending_here = Math.Max(head.data,
max_ending_here +
head.data);
// Update the maximum sum so far
max_so_far = Math.Max(max_ending_here,
max_so_far);
// Get to the next node
head = head.next;
}
// Return the maximum sum so far
return max_so_far;
}
// Driver code
public static void Main(String[] args)
{
// Create the linked list
Node head = null;
head = append(head, -2);
head = append(head, -3);
head = append(head, 4);
head = append(head, -1);
head = append(head, -2);
head = append(head, 1);
head = append(head, 5);
head = append(head, -3);
Console.Write(MaxContiguousNodeSum(head));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// JavaScript implementation of the approach
// Structure of a node of the linked list
class Node {
constructor() {
this.data = 0;
this.next = null;
}
}
/* Given a reference (pointer to pointer) to the head
of a list and an int, appends a new node at the end */
function append( head_ref, new_data)
{
// Allocate node
var new_node = new Node();
var last = head_ref; /* used in step 5*/
// Put in the data
new_node.data = new_data;
/* This new node is going to be
the last node, so make next of
it as null*/
new_node.next = null;
/* If the Linked List is empty,
then make the new node as head */
if (head_ref == null)
{
head_ref = new_node;
return head_ref;
}
// Else traverse till the last node
while (last.next != null)
last = last.next;
// Change the next of last node
last.next = new_node;
return head_ref;
}
// Function to return the maximum contiguous
// nodes sum in the given linked list
function MaxContiguousNodeSum( head)
{
// If the list is empty
if (head == null)
return 0;
// If the list contains a single element
if (head.next == null)
return head.data;
// max_ending_here will store the maximum sum
// ending at the current node, currently it
// will be initialised to the maximum sum ending
// at the first node which is the first node's value
let max_ending_here = head.data;
// max_so_far will store the maximum sum of
// contiguous nodes so far which is the required
// answer at the end of the linked list traversal
let max_so_far = head.data;
// Starting from the second node
head = head.next;
// While there are nodes in linked list
while (head != null)
{
// max_ending_here will be the maximum of either
// the current node's value or the current node's
// value added with the max_ending_here
// for the previous node
max_ending_here = Math.max(head.data,
max_ending_here + head.data);
// Update the maximum sum so far
max_so_far = Math.max(max_ending_here, max_so_far);
// Get to the next node
head = head.next;
}
// Return the maximum sum so far
return max_so_far;
}
// Driver Code
// Create the linked list
var head = null;
head = append(head, -2);
head = append(head, -3);
head = append(head, 4);
head = append(head, -1);
head = append(head, -2);
head = append(head, 1);
head = append(head, 5);
head = append(head, -3);
document.write(MaxContiguousNodeSum(head));
</script>
Similar Reads
Maximum sum of K consecutive nodes in the given Linked List Given a linked list, the task is to find the maximum sum obtained by adding any k consecutive nodes of linked list. Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL, K = 5 Output: 20 Maximum sum is obtained by adding last 5 nodes Input: 2 -> 5 -> 3 -> 6 -> 4 -> 1
8 min read
Delete continuous nodes with sum K from a given linked list Given a singly linked list and an integer K, the task is to remove all the continuous set of nodes whose sum is K from the given linked list. Print the updated linked list after the removal. If no such deletion can occur, print the original Linked list. Examples: Input: Linked List: 1 -> 2 ->
11 min read
Maximum sum of Sublist with composite number nodes in a Linked List Given a linked list, the task is to find the maximum sum of a sublist with composite number nodes. A composite number is any positive integer greater than 1 that is not a prime number. Examples: Input: List: 1 -> 4 -> 8 -> 7 -> 6 -> 6 -> 9Output: 21Explanation: The sublist with com
3 min read
Maximum distance between Peaks in given Linked List Given a linked list of length n, the task is to determine the maximum distance between two consecutive peaks of the given linked list. A peak is a node with a value greater than its neighbours. The distance between two nodes is defined as the number of nodes present between them. Examples:Input: Lin
11 min read
Longest Continuous Sequence with difference K in Linked List Given a linked list and given an integer K, the task is to find the length of the longest continuous sequence in a linked list that has a difference of k. Examples: Input: 4 -> 1 -> 8 -> 5 -> 2 -> 4, K = 3 Output: 3 Explanation: The longest continuous sequence with a difference of 3 i
9 min read
Find the sum of last n nodes of the given Linked List Given a linked list and a number n. Find the sum of the last n nodes of the linked list.Constraints: 0 <= n <= number of nodes in the linked list. Examples: Input : 10->6->8->4->12, n = 2 Output : 16 Sum of last two nodes: 12 + 4 = 16 Input : 15->7->9->5->16->14, n =
15+ min read
Find extra node in the second Linked list Given two Linked list L1 and L2. The second list L2 contains all the nodes of L1 along with 1 extra node. The task is to find that extra node. Examples: Input: L1 = 17 -> 7 -> 6 -> 16 L2 = 17 -> 7 -> 6 -> 16 -> 15 Output: 15 Explanation: Element 15 is not present in the L1 listI
7 min read
Delete a given node in Linked List under given constraints Given a Singly Linked List, write a function to delete a given node. Your function must follow following constraints: 1) It must accept a pointer to the start node as the first parameter and node to be deleted as the second parameter i.e., a pointer to head node is not global. 2) It should not retur
11 min read
Insert a Node at the end of Doubly Linked List Given a Doubly Linked List, the task is to insert a new node at the end of the linked list.Examples: Input: Linked List = 1 <-> 2 <-> 3, NewNode = 4Output: Linked List = 1 <-> 2 <-> 3 <-> 4Input: Linked List = NULL, NewNode = 1Output: Linked List = 1Approach: Inserting
9 min read
Insert node into the middle of the linked list Given a linked list containing n nodes. The problem is to insert a new node with data x in the middle of the list. If n is even, then insert the new node after the (n/2)th node, else insert the new node after the (n+1)/2th node.Examples: Input: LinkedList = 1->2->4 , x = 3Output: 1->2->3
14 min read