Maximum cost path in an Undirected Graph such that no edge is visited twice in a row
Last Updated :
15 Jul, 2025
Given an undirected graph having N vertices and M edges and each vertex is associated with a cost and a source vertex S is given. The task is to find the maximum cost path from source vertex S such that no edge is visited consecutively 2 or more times.
Examples:
Input: N = 5, M = 5, source = 1, cost[] = {2, 2, 8, 6, 9}, Below is the given graph:
Output: 21
Explanation:
The maximum cost path matrix is given as:
1 -> 2 -> 0 -> 1 -> 4
Cost = 2 + 8 + 2 + 2 + 9 = 21
Input: N = 8, M = 8, source = 3, cost[] = {10, 11, 4, 12, 3, 4, 7, 9}
Output: 46
Explanation:
The maximum cost path matrix is given as:
3 -> 0 -> 2 -> 1 -> 7
Approach: The idea is to check if there exists a loop exists in the graph, then all vertices of the loop need to be traversed and then traverse graph towards the leaf nodes with the maximum cost. And if the loop does not exist then the problem statement converts to find maximum cost path in any directed graph.
Below are the declaration used in the program:
- dp[i]: stores the total cost to traverse the node 'i' and all it's children node.
- vis[i]: marks the nodes which have been visited.
- canTake: stores the resultant sum of all node of maximum cost path excluding the leaf vertex and its children node, if it exists.
- best: stores the cost of a maximum cost leaf node and its children node(if it exists).
- check: boolean variable used as a flag to find a loop in the graph, its value changes to 0 when the loop is found.
Below are the steps:
- Perform DFS traversal with flag variable check set to '1' initially denoting no loop found.
- Simultaneously build the dp[] for each node with the maximum cost updated till that traversed node.
- If the adjacent node is found to be already visited and it is not the parent node then the loop is found and set the value of the check to 0.
- Add the cost of all nodes of the loop to canTake.
- After traversing adjacent nodes of the traversing node, no loop is found, then it represents the cost of the path leading from loop to leaf vertex and updates best to dp[i] if dp[i] is greater than best.
- After traversal of the graph, print the sum of canTake and best.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// To store the resulting
// sum of the cost
int canTake;
// To store largest
// cost leaf vertex
int best;
vector<int> dp;
vector<bool> vis;
// DFS Traversal to find the update
// the maximum cost of from any
// node to leaf
int dfs(vector<vector<int> >& g,
int* cost, int u, int pre)
{
// Mark vertex as visited
vis[u] = true;
// Store vertex initial cost
dp[u] = cost[u];
// Initially assuming edge
// not to be traversed
bool check = 1;
int cur = cost[u];
for (auto& x : g[u]) {
// Back edge found so,
// edge can be part of
// traversal
if (vis[x] && x != pre) {
check = 0;
}
// New vertex is found
else if (!vis[x]) {
// Bitwise AND the current
// check with the returned
// check by the previous
// DFS Call
check &= dfs(g, cost, x, u);
// Adds parent and its
// children cost
cur = max(cur,
cost[u] + dp[x]);
}
}
// Updates total cost of parent
// including child nodes
dp[u] = cur;
// Edge is part of the cycle
if (!check) {
// Add cost of vertex
// to the answer
canTake += cost[u];
}
else {
// Updates the largest
// cost leaf vertex
best = max(best, dp[u]);
}
return check;
}
// Function to find the maximum cost
// from source vertex such that no
// two edges is traversed twice
int FindMaxCost(vector<vector<int> >& g,
int* cost, int source)
{
// DFS Call
dfs(g, cost, source, -1);
// Print the maximum cost
cout << canTake + best;
}
// Driver Code
int main()
{
int n = 5, m = 5;
dp.resize(n+1);
vis.resize(n+1);
// Cost Array
int cost[] = { 2, 2, 8, 6, 9 };
vector<vector<int> > g(n);
// Given Graph
g[0].push_back(1);
g[1].push_back(0);
g[0].push_back(2);
g[2].push_back(0);
g[0].push_back(3);
g[3].push_back(0);
g[1].push_back(2);
g[2].push_back(1);
g[1].push_back(4);
g[4].push_back(1);
// Given Source Node
int source = 1;
// Function Call
FindMaxCost(g, cost, source);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
static int N = 100000;
// To store the resulting
// sum of the cost
static int canTake;
// To store largest
// cost leaf vertex
static int best;
static int []dp = new int[N];
static boolean []vis = new boolean[N];
// DFS Traversal to find the update
// the maximum cost of from any
// node to leaf
static boolean dfs(Vector<Integer> []g,
int []cost, int u, int pre)
{
// Mark vertex as visited
vis[u] = true;
// Store vertex initial cost
dp[u] = cost[u];
// Initially assuming edge
// not to be traversed
boolean check = true;
int cur = cost[u];
for(int x : g[u])
{
// Back edge found so,
// edge can be part of
// traversal
if (vis[x] && x != pre)
{
check = false;
}
// New vertex is found
else if (!vis[x])
{
// Bitwise AND the current
// check with the returned
// check by the previous
// DFS Call
check = dfs(g, cost, x, u) ?
false : true;
// Adds parent and its
// children cost
cur = Math.max(cur, cost[u] +
dp[x]);
}
}
// Updates total cost of parent
// including child nodes
dp[u] = cur;
// Edge is part of the cycle
if (!check)
{
// Add cost of vertex
// to the answer
canTake += cost[u];
}
else
{
// Updates the largest
// cost leaf vertex
best = Math.max(best, dp[u]);
}
return check;
}
// Function to find the maximum cost
// from source vertex such that no
// two edges is traversed twice
static void FindMaxCost(Vector<Integer> [] g,
int []cost, int source)
{
// DFS call
dfs(g, cost, source, -1);
// Print the maximum cost
System.out.print(canTake + best);
}
// Driver Code
public static void main(String[] args)
{
int n = 5, m = 5;
// Cost Array
int cost[] = { 2, 2, 8, 6, 9 };
@SuppressWarnings("unchecked")
Vector<Integer> []g = new Vector[n];
for(int i = 0; i < g.length; i++)
g[i] = new Vector<Integer>();
// Given Graph
g[0].add(1);
g[1].add(0);
g[0].add(2);
g[2].add(0);
g[0].add(3);
g[3].add(0);
g[1].add(2);
g[2].add(1);
g[1].add(4);
g[4].add(1);
// Given Source Node
int source = 1;
// Function call
FindMaxCost(g, cost, source);
}
}
// This code is contributed by Amit Katiyar
Python3
# Python3 program for the above approach
N = 100000
# To store the resulting
# sum of the cost
canTake = 0
# To store largest
# cost leaf vertex
best = 0
dp = [0 for i in range(N)]
vis = [0 for i in range(N)]
# DFS Traversal to find the update
# the maximum cost of from any
# node to leaf
def dfs(g, cost, u, pre):
global canTake, best
# Mark vertex as visited
vis[u] = True
# Store vertex initial cost
dp[u] = cost[u]
# Initially assuming edge
# not to be traversed
check = 1
cur = cost[u]
for x in g[u]:
# Back edge found so,
# edge can be part of
# traversal
if (vis[x] and x != pre):
check = 0
# New vertex is found
elif (not vis[x]):
# Bitwise AND the current
# check with the returned
# check by the previous
# DFS Call
check &= dfs(g, cost, x, u)
# Adds parent and its
# children cost
cur = max(cur, cost[u] + dp[x])
# Updates total cost of parent
# including child nodes
dp[u] = cur
# Edge is part of the cycle
if (not check):
# Add cost of vertex
# to the answer
canTake += cost[u]
else:
# Updates the largest
# cost leaf vertex
best = max(best, dp[u])
return check
# Function to find the maximum cost
# from source vertex such that no
# two edges is traversed twice
def FindMaxCost(g, cost, source):
# DFS Call
dfs(g, cost, source, -1)
# Print the maximum cost
print(canTake + best)
# Driver Code
if __name__=='__main__':
n = 5
m = 5
# Cost Array
cost = [ 2, 2, 8, 6, 9 ]
g = [[] for i in range(n)]
# Given Graph
g[0].append(1)
g[1].append(0)
g[0].append(2)
g[2].append(0)
g[0].append(3)
g[3].append(0)
g[1].append(2)
g[2].append(1)
g[1].append(4)
g[4].append(1)
# Given Source Node
source = 1
# Function Call
FindMaxCost(g, cost, source)
# This code is contributed by rutvik_56
C#
// C# program for
// the above approach
using System;
using System.Collections.Generic;
class GFG{
static int N = 100000;
// To store the resulting
// sum of the cost
static int canTake;
// To store largest
// cost leaf vertex
static int best;
static int []dp = new int[N];
static bool []vis = new bool[N];
// DFS Traversal to find the update
// the maximum cost of from any
// node to leaf
static bool dfs(List<int> []g,
int []cost,
int u, int pre)
{
// Mark vertex as visited
vis[u] = true;
// Store vertex initial cost
dp[u] = cost[u];
// Initially assuming edge
// not to be traversed
bool check = true;
int cur = cost[u];
foreach(int x in g[u])
{
// Back edge found so,
// edge can be part of
// traversal
if (vis[x] && x != pre)
{
check = false;
}
// New vertex is found
else if (!vis[x])
{
// Bitwise AND the current
// check with the returned
// check by the previous
// DFS Call
check = dfs(g, cost, x, u) ?
false : true;
// Adds parent and its
// children cost
cur = Math.Max(cur, cost[u] + dp[x]);
}
}
// Updates total cost of parent
// including child nodes
dp[u] = cur;
// Edge is part of the cycle
if (!check)
{
// Add cost of vertex
// to the answer
canTake += cost[u];
}
else
{
// Updates the largest
// cost leaf vertex
best = Math.Max(best, dp[u]);
}
return check;
}
// Function to find the maximum cost
// from source vertex such that no
// two edges is traversed twice
static void FindMaxCost(List<int> [] g,
int []cost, int source)
{
// DFS call
dfs(g, cost, source, -1);
// Print the maximum cost
Console.Write(canTake + best);
}
// Driver Code
public static void Main(String[] args)
{
int n = 5, m = 5;
// Cost Array
int []cost = {2, 2, 8, 6, 9};
List<int> []g = new List<int>[n];
for(int i = 0; i < g.Length; i++)
g[i] = new List<int>();
// Given Graph
g[0].Add(1);
g[1].Add(0);
g[0].Add(2);
g[2].Add(0);
g[0].Add(3);
g[3].Add(0);
g[1].Add(2);
g[2].Add(1);
g[1].Add(4);
g[4].Add(1);
// Given Source Node
int source = 1;
// Function call
FindMaxCost(g, cost, source);
}
}
// This code is contributed by Princi Singh
JavaScript
<script>
// Javascript program for
// the above approach
var N = 100000;
// To store the resulting
// sum of the cost
var canTake = 0;
// To store largest
// cost leaf vertex
var best = 0;
var dp = Array(N).fill(0);
var vis = Array(N).fill(false);
// DFS Traversal to find the update
// the maximum cost of from any
// node to leaf
function dfs(g, cost, u, pre)
{
// Mark vertex as visited
vis[u] = true;
// Store vertex initial cost
dp[u] = cost[u];
// Initially assuming edge
// not to be traversed
var check = true;
var cur = cost[u];
for(var x of g[u])
{
// Back edge found so,
// edge can be part of
// traversal
if (vis[x] && x != pre)
{
check = false;
}
// New vertex is found
else if (!vis[x])
{
// Bitwise AND the current
// check with the returned
// check by the previous
// DFS Call
check = dfs(g, cost, x, u) ?
false : true;
// Adds parent and its
// children cost
cur = Math.max(cur, cost[u] + dp[x]);
}
}
// Updates total cost of parent
// including child nodes
dp[u] = cur;
// Edge is part of the cycle
if (!check)
{
// push cost of vertex
// to the answer
canTake += cost[u];
}
else
{
// Updates the largest
// cost leaf vertex
best = Math.max(best, dp[u]);
}
return check;
}
// Function to find the maximum cost
// from source vertex such that no
// two edges is traversed twice
function FindMaxCost(g, cost, source)
{
// DFS call
dfs(g, cost, source, -1);
// Print the maximum cost
document.write(canTake + best);
}
// Driver Code
var n = 5, m = 5;
// Cost Array
var cost = [2, 2, 8, 6, 9];
var g = Array.from(Array(n), ()=>Array());
// Given Graph
g[0].push(1);
g[1].push(0);
g[0].push(2);
g[2].push(0);
g[0].push(3);
g[3].push(0);
g[1].push(2);
g[2].push(1);
g[1].push(4);
g[4].push(1);
// Given Source Node
var source = 1;
// Function call
FindMaxCost(g, cost, source);
</script>
Time Complexity: O(N + M) where N is a number of vertices and M is the number of edges.
Auxiliary Space: O(N + M) where N is a number of vertices and M is a number of edges.
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