Question:
Given an undirected tree with N nodes ( 2 <= N <= 100,000 ) and N-1 edges, how can I find two non-intersecting paths with maximum product?
Example:
6
1-2
2-3
2-4
5-4
6-4
Answer: 4
I need to find O(N) solution. I wrote O(n^2) solution, but it isn’t accepting it. Here is my O(n^2) solution:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main{
private static int currentMax;
private static List<List<Integer>> tree;
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("src/input.txt"));
int N = Integer.parseInt(reader.readLine()) - 1;
int[][] edges = new int[N][2];
tree = new ArrayList<>();
for (int i = 0; i < N; i++) {
String[] line = reader.readLine().split(" ");
edges[i][0] = Integer.parseInt(line[0]);
edges[i][1] = Integer.parseInt(line[1]);
}
for(int i = 0; i < N + 2; i++)
tree.add(i, new ArrayList<>());
for (int[] edge : edges) {
tree.get(edge[0]).add(edge[1]);
tree.get(edge[1]).add(edge[0]);
}
long res = 0;
int path1, path2;
for(int i = 1; i < N + 2; i++) {
for(int j = 0; j < tree.get(i).size(); j++) {
currentMax = 0;
path1 = dfs(tree.get(i).get(j), i);
currentMax = 0;
path2 = dfs(i, tree.get(i).get(j));
res = Math.max(res, (long) path1 * path2);
}
System.out.println(i);
}
System.out.println(res);
reader.close();
}
private static int dfs(int root, int visited) {
int fisrtMax = 0, secMax = 0;
int total = 0;
for(int i = 0; i < tree.get(root).size(); i++) {
if (tree.get(root).get(i) == visited)
continue;
total = Math.max(total, dfs(tree.get(root).get(i), root));
if (currentMax > fisrtMax) {
secMax = fisrtMax;
fisrtMax = currentMax;
} else if(currentMax > secMax)
secMax = currentMax;
}
if (fisrtMax + secMax > total)
total = fisrtMax + secMax;
currentMax = fisrtMax + 1;
return total;
}
}