You are given an array with elements. You create a graph with vertices using as follows:
For any pair of indices where , if , then add an undirected edge between vertices and .
In graph , find the maximum possible size of set (of vertices in G) such that there exists an edge between every pair of vertices that are available in .
Example:
Input: n=3, arr=[2,1,3]
Output: 2
Approach
Java
import java.util.Arrays;public class InversionGraphs {public static void main(String args[]) {int len = 3;int array[] = { 2, 1, 3 };int result = inversionGraphs(len, array);System.out.println(result);}private static int inversionGraphs(int len, int[] array) {if (array == null || len < 2)return len;int[] indices = new int[len + 1];Arrays.fill(indices, -1);int length = 0;for (int i = 0; i < len; i++) {int newLength = binarySearch(1, length, indices, array, array[i]);indices[newLength] = i;length = Math.max(length, newLength);}return length;}private static int binarySearch(int startIdx, int endIdx, int indices[], int array[], int num) {if (startIdx > endIdx)return startIdx;int middleIdx = startIdx + (endIdx - startIdx) / 2;if (array[indices[middleIdx]] > num) {startIdx = middleIdx + 1;} else {endIdx = middleIdx - 1;}return binarySearch(startIdx, endIdx, indices, array, num);}}
No comments:
Post a Comment