Given a directed, weighted graph with n nodes and e edges, the task is to find the maximum product of edge weights in any path starting from node 1 andendingat node n.
Note: A path is a sequence of nodes starting and ending at particular nodes. The Graph does not contain loops and parallel edges.
Example:
Input:
Output: 224 Explanation: 7 * 4 * 8 = 224, as we have to travel from 1 to n i.e., 1 to 5 = > 1 - > 4 - > 2 - > 5
Approach: This can be solved with the following idea:
The idea is to apply the Dijkstra algorithm and change the meaning of the array which in the original algorithm used to store the value of the minimum sum of edge weights required to reach the current node to the maximum product of edge weights among all possible paths to reach the current node. We will update the update logic of Dijkstra to store the maximum product of edges in the array.
Steps involved in the implementation of code:
Initialize a priority queue (pq) ( Max heap ) of pair ( Pair as it contains the first value of the maximum edge encountered and second current node).
Insert into the priority queue a pair (1, 1) -> (1) denoting starting node 1 ( No edges encountered, and as we are going to do multiplication we need to initialize the first node with value 1)
Initialize an array of size = no. of nodes, denoting the maximum edge weight encountered from node 1 to the current node.
Run a while loop while (pq.size() > 0):
Pair p = pq.top() ;
pq.pop() (removing top element from the priority queue)
for (nodes in adjacency list):
update logic: update the array of the maximum product if the product of the current edge weight and previous node maximum product is greater than the current node maximum product value.
Run a loop on the array to find the maximum answer.
Below is the implementation of the above approach:
C++
// C++ Implementation of the above code#include<bits/stdc++.h>usingnamespacestd;// Function to find maximum weight// of graphfrom 1 to nintmax_product_of_edges_in_path(intn,vector<vector<int>>&roads){// Declaring adjacency listvector<vector<pair<int,int>>>adj(n+1);// Construction of adjacency list using// the information of edgesfor(inti=0;i<roads.size();i++){adj[roads[i][0]].push_back({roads[i][1],roads[i][2]});// Directed graph : edge from// roads[i][0] -> roads[i][1]// of edge weight roads[i][2]}priority_queue<pair<int,int>>pq;// Normal dijkstrapq.push({1,1});vector<int>max_product(n+1,-1);max_product[1]=1;while(!pq.empty()){pair<int,int>p=pq.top();pq.pop();if(max_product[p.second]>p.first)continue;// Reduce extra iterations// as in dijkstrafor(autoit:adj[p.second]){// Update logic similar to// dijkstra but with// conditions changedif(p.first*it.second>max_product[it.first]){max_product[it.first]=p.first*it.second;pq.push({max_product[it.first],it.first});}}}returnmax_product[n];}// Driver codeintmain(){intn=5;vector<vector<int>>edges;edges.push_back({1,2,5});edges.push_back({1,3,6});edges.push_back({1,4,7});edges.push_back({4,2,4});edges.push_back({2,5,8});// Function callcout<<max_product_of_edges_in_path(n,edges)<<"\n";return0;}
Java
//Java Algorithm for the above approachimportjava.util.*;publicclassGFG{// Implementing Pair classpublicstaticclassPairimplementsComparable<Pair>{intfirst;intsecond;Pair(intfirst,intsecond){this.first=first;this.second=second;}publicintcompareTo(Pairob){if(this.first==ob.first){returnthis.second-ob.second;}returnthis.first-ob.first;}}// Function to find maximum weight// of graphfrom 1 to npublicstaticintmax_product_of_edges_in_path(intn,ArrayList<ArrayList<Integer>>roads){// Declaring adjacency listArrayList<Pair>[]adj=newArrayList[n+1];for(inti=0;i<n+1;i++){adj[i]=newArrayList<>();}// Construction of adjacency list using// the information of edgesfor(inti=0;i<roads.size();i++){adj[roads.get(i).get(0)].add(newPair(roads.get(i).get(1),roads.get(i).get(2)));;// Directed graph : edge from// roads[i][0] -> roads[i][1]// of edge weight roads[i][2]}PriorityQueue<Pair>pq=newPriorityQueue<>();// Normal dijkstrapq.add(newPair(1,1));int[]max_product=newint[n+1];Arrays.fill(max_product,-1);max_product[1]=1;while(!pq.isEmpty()){Pairp=pq.remove();if(max_product[p.second]>p.first)continue;// Reduce extra iterations// as in dijkstrafor(Pairit:adj[p.second]){// Update logic similar to// dijkstra but with// conditions changedif(p.first*it.second>max_product[it.first]){max_product[it.first]=p.first*it.second;pq.add(newPair(max_product[it.first],it.first));}}}returnmax_product[n];}// Driver Codepublicstaticvoidmain(String[]args){intn=5;ArrayList<ArrayList<Integer>>edges=newArrayList<ArrayList<Integer>>();edges.add(newArrayList<Integer>(){{add(1);add(2);add(5);}});edges.add(newArrayList<Integer>(){{add(1);add(3);add(6);}});edges.add(newArrayList<Integer>(){{add(1);add(4);add(7);}});edges.add(newArrayList<Integer>(){{add(4);add(2);add(4);}});edges.add(newArrayList<Integer>(){{add(2);add(5);add(8);}});// Function CallSystem.out.println(max_product_of_edges_in_path(n,edges));}}
Python
# python Algorithm for the above approachimportheapqdefmax_product_of_edges_in_path(n,roads):# Declaring adjacency listadj=[[]for_inrange(n+1)]# Construction of adjacency list using the information of edgesforroadinroads:adj[road[0]].append((road[1],road[2]))# Directed graph: edge from road[0] -> road[1] of edge weight road[2]pq=[]# priority queue using heapq module# Normal Dijkstra'sheapq.heappush(pq,(1,1))max_product=[-1]*(n+1)max_product[1]=1whilepq:p=heapq.heappop(pq)ifmax_product[p[1]]>p[0]:continue# Reduce extra iterations as in Dijkstra'sforitinadj[p[1]]:# Update logic similar to Dijkstra's but with conditions changedifp[0]*it[1]>max_product[it[0]]:max_product[it[0]]=p[0]*it[1]heapq.heappush(pq,(max_product[it[0]],it[0]))returnmax_product[n]# Driver codeif__name__=='__main__':n=5edges=[[1,2,5],[1,3,6],[1,4,7],[4,2,4],[2,5,8]]# Function callprint(max_product_of_edges_in_path(n,edges))# This code is generated by Chetan Bargal
C#
// C# code for the approachusingSystem;usingSystem.Collections.Generic;publicclassSolution{// Function to find maximum weight// of graphfrom 1 to npublicintMaxProductOfEdgesInPath(intn,int[][]roads){// Declaring adjacency listList<int[]>[]adj=newList<int[]>[n+1];for(inti=0;i<=n;i++){adj[i]=newList<int[]>();}// Construction of adjacency list using the information of edgesforeach(int[]roadinroads){adj[road[0]].Add(newint[]{road[1],road[2]});// Directed graph: edge from road[0] -> road[1] of edge weight road[2]}// Priority queue using SortedSetSortedSet<Tuple<int,int>>pq=newSortedSet<Tuple<int,int>>();// Normal Dijkstra'spq.Add(newTuple<int,int>(1,1));int[]maxProduct=newint[n+1];for(inti=0;i<=n;i++){maxProduct[i]=-1;}maxProduct[1]=1;while(pq.Count>0){Tuple<int,int>p=pq.Max;pq.Remove(p);if(maxProduct[p.Item2]>p.Item1){continue;}// Reduce extra iterations as in Dijkstra'sforeach(int[]itinadj[p.Item2]){// Update logic similar to Dijkstra's but with conditions changedif(p.Item1*it[1]>maxProduct[it[0]]){maxProduct[it[0]]=p.Item1*it[1];pq.Add(newTuple<int,int>(maxProduct[it[0]],it[0]));}}}returnmaxProduct[n];}}// Driver codepublicclassGFG{staticvoidMain(string[]args){intn=5;int[][]edges={newint[]{1,2,5},newint[]{1,3,6},newint[]{1,4,7},newint[]{4,2,4},newint[]{2,5,8}};// Function callSolutionsolution=newSolution();Console.WriteLine(solution.MaxProductOfEdgesInPath(n,edges));}}
JavaScript
// Javascript implementation of the above code// Function to find maximum weight// of graph from 1 to nfunctionmaxProductOfEdgesInPath(n,roads){// Declaring adjacency listconstadj=Array(n+1).fill().map(()=>[]);// Construction of adjacency list using// the information of edgesfor(leti=0;i<roads.length;i++){adj[roads[i][0]].push([roads[i][1],roads[i][2]]);// Directed graph: edge from// roads[i][0] -> roads[i][1]// of edge weight roads[i][2]}constpq=[];// Normal dijkstrapq.push([1,1]);constmaxProduct=Array(n+1).fill(-1);maxProduct[1]=1;while(pq.length>0){const[pFirst,pSecond]=pq.shift();if(maxProduct[pSecond]>pFirst)continue;// Reduce extra iterations// as in dijkstrafor(const[itFirst,itSecond]ofadj[pSecond]){// Update logic similar to// dijkstra but with// conditions changedif(pFirst*itSecond>maxProduct[itFirst]){maxProduct[itFirst]=pFirst*itSecond;pq.push([maxProduct[itFirst],itFirst]);}}}returnmaxProduct[n];}// Driver codeconstn=5;constedges=[[1,2,5],[1,3,6],[1,4,7],[4,2,4],[2,5,8],];// Function callconsole.log(maxProductOfEdgesInPath(n,edges));