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:
MyBatis with Spring
Spring Boot - Apache Kafka
Guide to Java Instrumentation
Generic Constructors in Java
LinkedHashSet trong Java hoạt động như thế nào?
Java Program to Implement TreeSet API
ArrayList trong java
Guava CharMatcher
HashMap trong Java hoạt động như thế nào?
Finding the Differences Between Two Lists in Java
Spring Boot Configuration with Jasypt
Merging Streams in Java
Hướng dẫn Java Design Pattern – Null Object
Java Program to Implement TreeMap API
How to Convert List to Map in Java
Java Program to Compute the Volume of a Tetrahedron Using Determinants
String Joiner trong Java 8
Java Program to Implement CopyOnWriteArrayList API
Java Program to Implement SimpeBindings API
Java – Write to File
Giới thiệu Google Guice – Binding
Immutable Objects in Java
Serialize Only Fields that meet a Custom Criteria with Jackson
Java Program to Generate Random Hexadecimal Byte
Java NIO2 Path API
Spring Boot - Exception Handling
Getting Started with Forms in Spring MVC
Set Interface trong Java
Wrapper Classes in Java
Getting Started with GraphQL and Spring Boot
Optional trong Java 8
Using a List of Values in a JdbcTemplate IN Clause