Largest subarray sum of all connected components in undirected graph
Last Updated :
12 Jul, 2025
Given an undirected graph with V vertices and E edges, the task is to find the maximum contiguous subarray sum among all the connected components of the graph.
Examples:
Input: E = 4, V = 7
Output:
Maximum subarray sum among all connected components = 5
Explanation:
Connected Components and maximum subarray sums are as follows:
[3, 2]: Maximum subarray sum = 3 + 2 = 5
[4, -2, 0]: Maximum subarray sum = 4
[-1, -5]: Maximum subarray sum = -1
So, Maximum contiguous subarray sum = 5
Input: E = 6, V = 10
Output:
Maximum subarray sum among all connected components = 9
Explanation:
Connected Components and maximum subarray sums are as follows:
[-3]: Maximum subarray sum = -3
[-2, 7, 1, -1]: Maximum subarray sum = 7 + 1 = 8
[4, 0, 5]: Maximum subarray sum = 4 + 0 + 5 = 9
[-4, 6]: Maximum subarray sum = 6
So, Maximum contiguous subarray sum = 9
Approach: The idea is to use Depth First Search Traversal to keep track of the connected components in the undirected graph as explained in this article. For each connected component, the array is analyzed and the maximum contiguous subarray sum is computed based on Kadane's Algorithm as explained in this article. A global variable is set that is compared at each iteration with the local sum values to obtain the final result.
Below is the implementation of the above approach:
C++
// C++ implementation to find
// largest subarray sum among
// all connected components
#include <bits/stdc++.h>
using namespace std;
// Function to traverse the undirected
// graph using the Depth first traversal
void depthFirst(int v, vector<int> graph[],
vector<bool>& visited,
vector<int>& storeChain)
{
// Marking the visited
// vertex as true
visited[v] = true;
// Store the connected chain
storeChain.push_back(v);
for (auto i : graph[v]) {
if (visited[i] == false) {
// Recursive call to
// the DFS algorithm
depthFirst(i, graph,
visited, storeChain);
}
}
}
// Function to return maximum
// subarray sum of each connected
// component using Kadane's Algorithm
int subarraySum(int arr[], int n)
{
int maxSubarraySum = arr[0];
int currentMax = arr[0];
// Following loop finds maximum
// subarray sum based on Kadane's
// algorithm
for (int i = 1; i < n; i++) {
currentMax = max(arr[i],
arr[i] + currentMax);
// Global maximum subarray sum
maxSubarraySum = max(maxSubarraySum,
currentMax);
}
// Returning the sum
return maxSubarraySum;
}
// Function to find the maximum subarray
// sum among all connected components
void maxSubarraySum(
vector<int> graph[], int vertices,
vector<int> values)
{
// Initializing boolean array
// to mark visited vertices
vector<bool> visited(1001, false);
// maxSum stores the
// maximum subarray sum
int maxSum = INT_MIN;
// Following loop invokes DFS algorithm
for (int i = 1; i <= vertices; i++) {
if (visited[i] == false) {
// Variable to hold
// temporary length
int sizeChain;
// Variable to hold temporary
// maximum subarray sum values
int tempSum;
// Container to store each chain
vector<int> storeChain;
// DFS algorithm
depthFirst(i, graph, visited, storeChain);
// Variable to hold each chain size
sizeChain = storeChain.size();
// Container to store values
// of vertices of individual chains
int chainValues[sizeChain + 1];
// Storing the values of each chain
for (int i = 0; i < sizeChain; i++) {
int temp = values[storeChain[i] - 1];
chainValues[i] = temp;
}
// Function call to find maximum
// subarray sum of current connection
tempSum = subarraySum(chainValues,
sizeChain);
// Conditional to store current
// maximum subarray sum
if (tempSum > maxSum) {
maxSum = tempSum;
}
}
}
// Printing global maximum subarray sum
cout << "Maximum subarray sum among all ";
cout << "connected components = ";
cout << maxSum;
}
// Driver code
int main()
{
// Initializing graph in the
// form of adjacency list
vector<int> graph[1001];
// Defining the number
// of edges and vertices
int E, V;
E = 4;
V = 7;
// Assigning the values for each
// vertex of the undirected graph
vector<int> values;
values.push_back(3);
values.push_back(2);
values.push_back(4);
values.push_back(-2);
values.push_back(0);
values.push_back(-1);
values.push_back(-5);
// Constructing the undirected graph
graph[1].push_back(2);
graph[2].push_back(1);
graph[3].push_back(4);
graph[4].push_back(3);
graph[4].push_back(5);
graph[5].push_back(4);
graph[6].push_back(7);
graph[7].push_back(6);
maxSubarraySum(graph, V, values);
return 0;
}
Java
// Java implementation to find
// largest subarray sum among
// all connected components
import java.io.*;
import java.util.*;
class GFG{
// Function to traverse the undirected
// graph using the Depth first traversal
static void depthFirst(int v, List<List<Integer>> graph,
boolean[] visited,
List<Integer> storeChain)
{
// Marking the visited
// vertex as true
visited[v] = true;
// Store the connected chain
storeChain.add(v);
for (int i : graph.get(v))
{
if (visited[i] == false)
{
// Recursive call to
// the DFS algorithm
depthFirst(i, graph,
visited,
storeChain);
}
}
}
// Function to return maximum
// subarray sum of each connected
// component using Kadane's Algorithm
static int subarraySum(int arr[],
int n)
{
int maxSubarraySum = arr[0];
int currentMax = arr[0];
// Following loop finds maximum
// subarray sum based on Kadane's
// algorithm
for (int i = 1; i < n; i++)
{
currentMax = Math.max(arr[i], arr[i] +
currentMax);
// Global maximum subarray sum
maxSubarraySum = Math.max(maxSubarraySum,
currentMax);
}
// Returning the sum
return maxSubarraySum;
}
// Function to find the maximum subarray
// sum among all connected components
static void maxSubarraySum(List<List<Integer>> graph,
int vertices,
List<Integer> values)
{
// Initializing boolean array
// to mark visited vertices
boolean[] visited = new boolean[1001];
// maxSum stores the
// maximum subarray sum
int maxSum = Integer.MIN_VALUE;
// Following loop invokes DFS
// algorithm
for (int i = 1; i <= vertices; i++)
{
if (visited[i] == false)
{
// Variable to hold
// temporary length
int sizeChain;
// Variable to hold temporary
// maximum subarray sum values
int tempSum;
// Container to store each chain
List<Integer> storeChain =
new ArrayList<Integer>();
// DFS algorithm
depthFirst(i, graph,
visited, storeChain);
// Variable to hold each
// chain size
sizeChain = storeChain.size();
// Container to store values
// of vertices of individual chains
int[] chainValues =
new int[sizeChain + 1];
// Storing the values of each chain
for (int j = 0; j < sizeChain; j++)
{
int temp = values.get(storeChain.get(j) - 1);
chainValues[j] = temp;
}
// Function call to find maximum
// subarray sum of current connection
tempSum = subarraySum(chainValues,
sizeChain);
// Conditional to store current
// maximum subarray sum
if (tempSum > maxSum)
{
maxSum = tempSum;
}
}
}
// Printing global maximum subarray sum
System.out.print("Maximum subarray sum among all ");
System.out.print("connected components = ");
System.out.print(maxSum);
}
// Driver code
public static void main(String[] args)
{
// Initializing graph in the
// form of adjacency list
List<List<Integer>> graph =
new ArrayList();
for (int i = 0; i < 1001; i++)
graph.add(new ArrayList<Integer>());
// Defining the number
// of edges and vertices
int E = 4, V = 7;
// Assigning the values for each
// vertex of the undirected graph
List<Integer> values =
new ArrayList<Integer>();
values.add(3);
values.add(2);
values.add(4);
values.add(-2);
values.add(0);
values.add(-1);
values.add(-5);
// Constructing the undirected
// graph
graph.get(1).add(2);
graph.get(2).add(1);
graph.get(3).add(4);
graph.get(4).add(3);
graph.get(4).add(5);
graph.get(5).add(4);
graph.get(6).add(7);
graph.get(7).add(6);
maxSubarraySum(graph, V, values);
}
}
// This code is contributed by jithin
Python3
# Python3 implementation to find
# largest subarray sum among
# all connected components
import sys
# Function to traverse
# the undirected graph
# using the Depth first
# traversal
def depthFirst(v, graph,
visited,
storeChain):
# Marking the visited
# vertex as true
visited[v] = True;
# Store the connected chain
storeChain.append(v);
for i in graph[v]:
if (visited[i] == False):
# Recursive call to
# the DFS algorithm
depthFirst(i, graph,
visited,
storeChain);
# Function to return maximum
# subarray sum of each connected
# component using Kadane's Algorithm
def subarraySum(arr, n):
maxSubarraySum = arr[0];
currentMax = arr[0];
# Following loop finds maximum
# subarray sum based on Kadane's
# algorithm
for i in range(1, n):
currentMax = max(arr[i],
arr[i] +
currentMax)
# Global maximum subarray sum
maxSubarraySum = max(maxSubarraySum,
currentMax);
# Returning the sum
return maxSubarraySum;
# Function to find the
# maximum subarray sum
# among all connected components
def maxSubarraySum(graph,
vertices, values):
# Initializing boolean array
# to mark visited vertices
visited = [False for i in range(1001)]
# maxSum stores the
# maximum subarray sum
maxSum = -sys.maxsize;
# Following loop invokes
# DFS algorithm
for i in range(1, vertices + 1):
if (visited[i] == False):
# Variable to hold
# temporary length
sizeChain = 0
# Variable to hold
# temporary maximum
# subarray sum values
tempSum = 0;
# Container to store
# each chain
storeChain = [];
# DFS algorithm
depthFirst(i, graph,
visited,
storeChain);
# Variable to hold each
# chain size
sizeChain = len(storeChain)
# Container to store values
# of vertices of individual chains
chainValues = [0 for i in range(sizeChain + 1)];
# Storing the values of each chain
for i in range(sizeChain):
temp = values[storeChain[i] - 1];
chainValues[i] = temp;
# Function call to find maximum
# subarray sum of current connection
tempSum = subarraySum(chainValues,
sizeChain);
# Conditional to store current
# maximum subarray sum
if (tempSum > maxSum):
maxSum = tempSum;
# Printing global maximum subarray sum
print("Maximum subarray sum among all ",
end = '');
print("connected components = ",
end = '')
print(maxSum)
if __name__=="__main__":
# Initializing graph in the
# form of adjacency list
graph = [[] for i in range(1001)]
# Defining the number
# of edges and vertices
E = 4;
V = 7;
# Assigning the values
# for each vertex of the
# undirected graph
values = [];
values.append(3);
values.append(2);
values.append(4);
values.append(-2);
values.append(0);
values.append(-1);
values.append(-5);
# Constructing the
# undirected graph
graph[1].append(2);
graph[2].append(1);
graph[3].append(4);
graph[4].append(3);
graph[4].append(5);
graph[5].append(4);
graph[6].append(7);
graph[7].append(6);
maxSubarraySum(graph, V, values);
# This code is contributed by rutvik_56
C#
// C# implementation to find
// largest subarray sum among
// all connected components
using System;
using System.Collections;
using System.Collections.Generic;
class GFG{
// Function to traverse the undirected
// graph using the Depth first traversal
static void depthFirst(int v, List<List<int>> graph,
bool[] visited,
List<int> storeChain)
{
// Marking the visited
// vertex as true
visited[v] = true;
// Store the connected chain
storeChain.Add(v);
foreach (int i in graph[v])
{
if (visited[i] == false)
{
// Recursive call to
// the DFS algorithm
depthFirst(i, graph,
visited,
storeChain);
}
}
}
// Function to return maximum
// subarray sum of each connected
// component using Kadane's Algorithm
static int subarraySum(int []arr,
int n)
{
int maxSubarraySum = arr[0];
int currentMax = arr[0];
// Following loop finds maximum
// subarray sum based on Kadane's
// algorithm
for(int i = 1; i < n; i++)
{
currentMax = Math.Max(arr[i], arr[i] +
currentMax);
// Global maximum subarray sum
maxSubarraySum = Math.Max(maxSubarraySum,
currentMax);
}
// Returning the sum
return maxSubarraySum;
}
// Function to find the maximum subarray
// sum among all connected components
static void maxSubarraySum(List<List<int>> graph,
int vertices,
List<int> values)
{
// Initializing boolean array
// to mark visited vertices
bool[] visited = new bool[1001];
// maxSum stores the
// maximum subarray sum
int maxSum = -1000000;
// Following loop invokes DFS
// algorithm
for(int i = 1; i <= vertices; i++)
{
if (visited[i] == false)
{
// Variable to hold
// temporary length
int sizeChain;
// Variable to hold temporary
// maximum subarray sum values
int tempSum;
// Container to store each chain
List<int> storeChain = new List<int>();
// DFS algorithm
depthFirst(i, graph,
visited, storeChain);
// Variable to hold each
// chain size
sizeChain = storeChain.Count;
// Container to store values
// of vertices of individual chains
int[] chainValues = new int[sizeChain + 1];
// Storing the values of each chain
for(int j = 0; j < sizeChain; j++)
{
int temp = values[storeChain[j] - 1];
chainValues[j] = temp;
}
// Function call to find maximum
// subarray sum of current connection
tempSum = subarraySum(chainValues,
sizeChain);
// Conditional to store current
// maximum subarray sum
if (tempSum > maxSum)
{
maxSum = tempSum;
}
}
}
// Printing global maximum subarray sum
Console.Write("Maximum subarray sum among all ");
Console.Write("connected components = ");
Console.Write(maxSum);
}
// Driver code
public static void Main(string[] args)
{
// Initializing graph in the
// form of adjacency list
List<List<int>> graph = new List<List<int>>();
for(int i = 0; i < 1001; i++)
graph.Add(new List<int>());
// Defining the number
// of edges and vertices
int V = 7;
// Assigning the values for each
// vertex of the undirected graph
List<int> values = new List<int>();
values.Add(3);
values.Add(2);
values.Add(4);
values.Add(-2);
values.Add(0);
values.Add(-1);
values.Add(-5);
// Constructing the undirected
// graph
graph[1].Add(2);
graph[2].Add(1);
graph[3].Add(4);
graph[4].Add(3);
graph[4].Add(5);
graph[5].Add(4);
graph[6].Add(7);
graph[7].Add(6);
maxSubarraySum(graph, V, values);
}
}
// This code is contributed by pratham76
JavaScript
<script>
// Javascript implementation to find
// largest subarray sum among
// all connected components
// Function to traverse the undirected
// graph using the Depth first traversal
function depthFirst(v, graph, visited, storeChain)
{
// Marking the visited
// vertex as true
visited[v] = true;
// Store the connected chain
storeChain.push(v);
for(let i = 0; i < graph[v].length; i++)
{
if (visited[graph[v][i]] == false)
{
// Recursive call to
// the DFS algorithm
depthFirst(graph[v][i], graph,
visited,
storeChain);
}
}
}
// Function to return maximum
// subarray sum of each connected
// component using Kadane's Algorithm
function subarraySum(arr, n)
{
let maxSubarraySum = arr[0];
let currentMax = arr[0];
// Following loop finds maximum
// subarray sum based on Kadane's
// algorithm
for(let i = 1; i < n; i++)
{
currentMax = Math.max(arr[i], arr[i] +
currentMax);
// Global maximum subarray sum
maxSubarraySum = Math.max(maxSubarraySum,
currentMax);
}
// Returning the sum
return maxSubarraySum;
}
// Function to find the maximum subarray
// sum among all connected components
function maxSubarraySum(graph, vertices, values)
{
// Initializing boolean array
// to mark visited vertices
let visited = new Array(1001);
visited.fill(false);
// maxSum stores the
// maximum subarray sum
let maxSum = -1000000;
// Following loop invokes DFS
// algorithm
for(let i = 1; i <= vertices; i++)
{
if (visited[i] == false)
{
// Variable to hold
// temporary length
let sizeChain;
// Variable to hold temporary
// maximum subarray sum values
let tempSum;
// Container to store each chain
let storeChain = [];
// DFS algorithm
depthFirst(i, graph,
visited, storeChain);
// Variable to hold each
// chain size
sizeChain = storeChain.length;
// Container to store values
// of vertices of individual chains
let chainValues = new Array(sizeChain + 1);
// Storing the values of each chain
for(let j = 0; j < sizeChain; j++)
{
let temp = values[storeChain[j] - 1];
chainValues[j] = temp;
}
// Function call to find maximum
// subarray sum of current connection
tempSum = subarraySum(chainValues,
sizeChain);
// Conditional to store current
// maximum subarray sum
if (tempSum > maxSum)
{
maxSum = tempSum;
}
}
}
// Printing global maximum subarray sum
document.write("Maximum subarray sum among all ");
document.write("connected components = ");
document.write(maxSum);
}
// Initializing graph in the
// form of adjacency list
let graph = [];
for(let i = 0; i < 1001; i++)
graph.push([]);
// Defining the number
// of edges and vertices
let V = 7;
// Assigning the values for each
// vertex of the undirected graph
let values = [];
values.push(3);
values.push(2);
values.push(4);
values.push(-2);
values.push(0);
values.push(-1);
values.push(-5);
// Constructing the undirected
// graph
graph[1].push(2);
graph[2].push(1);
graph[3].push(4);
graph[4].push(3);
graph[4].push(5);
graph[5].push(4);
graph[6].push(7);
graph[7].push(6);
maxSubarraySum(graph, V, values);
// This code is contributed by suresh07.
</script>
OutputMaximum subarray sum among all connected components = 5
Time Complexity: O(V2)
The DFS algorithm takes O(V + E) time to run, where V, E are the vertices and edges of the undirected graph. Further, the maximum contiguous subarray sum is found at each iteration that takes an additional O(V) to compute and return the result based on Kadane's Algorithm. Hence, the overall complexity is O(V2)
Auxiliary Space: O(V)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem