This Java program Implements Maximum Length Chain Of Pairs.Given n pairs of numbers. In every pair, the first number is always smaller than the second number. A pair (c, d) can follow another pair (a, b) if b < c. Chain of pairs can be formed in this fashion. Find the longest chain which can be formed from a given set of pairs. Here is the source code of the Java Program to Implement Maximum Length Chain Of Pairs.The Java program is successfully compiled and run on a Linux system. The program output is also shown below.
public class MaxLengthChainOfPairs
{
public int maxChainLength(PairVal pair_arr[], int n)
{
int i, j, max = 0;
int MaxChainLen[] = new int[n];
for (i = 0; i < n; i++)
{
MaxChainLen[i] = 1;
}
for (i = 0; i < n; i++)
{
for (j = 0; j < i; j++)
{
if (pair_arr[i].a > pair_arr[j].b && MaxChainLen[i] < MaxChainLen[j] + 1)
MaxChainLen[i] = MaxChainLen[j] + 1;
}
}
for (i = 0; i < n; i++)
{
if (max < MaxChainLen[i])
max = MaxChainLen[i];
}
return max;
}
public static void main(String... arg)
{
PairVal pair_arr[] = new PairVal[4];
pair_arr[0] = new PairVal(5, 24);
pair_arr[1] = new PairVal(15, 25);
pair_arr[2] = new PairVal(27, 40);
pair_arr[3] = new PairVal(50, 60);
int n = 4;
MaxLengthChainOfPairs maxLengthChainOfPairs = new MaxLengthChainOfPairs();
System.out.println("the length of maximum size chain is "
+ maxLengthChainOfPairs.maxChainLength(pair_arr, n));
}
}
class PairVal
{
int a;
int b;
PairVal(int a, int b)
{
this.a = a;
this.b = b;
}
}
$ javac MaxLengthChainOfPairs.java $ java MaxLengthChainOfPairs the length of maximum size chain is 3
Related posts:
Implementing a Runnable vs Extending a Thread
Giới thiệu Google Guice – Binding
Transaction Propagation and Isolation in Spring @Transactional
Java Program to Find Inverse of a Matrix
Spring Boot - Internationalization
Java Program to Check Whether an Undirected Graph Contains a Eulerian Path
Uploading MultipartFile with Spring RestTemplate
Java Program to Compute Cross Product of Two Vectors
Comparing Two HashMaps in Java
Java Program to Implement the Program Used in grep/egrep/fgrep
Giới thiệu Design Patterns
Spring Data MongoDB Transactions
How to Delay Code Execution in Java
Java Program to Test Using DFS Whether a Directed Graph is Weakly Connected or Not
Phân biệt JVM, JRE, JDK
Java Program to Find a Good Feedback Edge Set in a Graph
Java Program to Use rand and srand Functions
Một số tính năng mới về xử lý ngoại lệ trong Java 7
Spring Boot - CORS Support
Dynamic Proxies in Java
Introduction to Apache Commons Text
So sánh HashMap và HashSet trong Java
Java Program to Perform Quick Sort on Large Number of Elements
Array to String Conversions
Java Byte Array to InputStream
The DAO with Spring and Hibernate
Deploy a Spring Boot App to Azure
Convert String to Byte Array and Reverse in Java
Ways to Iterate Over a List in Java
Spring – Injecting Collections
Spring Boot - Apache Kafka
Tạo ứng dụng Java RESTful Client với thư viện Retrofit