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:
Introduction to Spring Data MongoDB
Java Program to Implement RoleList API
Quản lý bộ nhớ trong Java với Heap Space vs Stack
Spring Cloud – Bootstrapping
Hướng dẫn sử dụng Lớp FilePermission trong java
Spring WebClient and OAuth2 Support
Quick Guide to Spring MVC with Velocity
Java NIO2 Path API
Quick Guide to Spring Bean Scopes
Spring Security with Maven
Java Program to Check whether Directed Graph is Connected using BFS
Guide to Java 8’s Collectors
REST Web service: Basic Authentication trong Jersey 2.x
New Features in Java 11
Java Program to Generate All Pairs of Subsets Whose Union Make the Set
How to Store Duplicate Keys in a Map in Java?
“Stream has already been operated upon or closed” Exception in Java
Java Program to Test Using DFS Whether a Directed Graph is Strongly Connected or Not
Java – Byte Array to Reader
Converting a Stack Trace to a String in Java
Prevent Cross-Site Scripting (XSS) in a Spring Application
Removing all duplicates from a List in Java
Java Program to Generate a Random Subset by Coin Flipping
Spring Boot - Creating Docker Image
Java Program to Find Transpose of a Graph Matrix
Converting String to Stream of chars
Functional Interfaces in Java 8
Custom Thread Pools In Java 8 Parallel Streams
Getting the Size of an Iterable in Java
Query Entities by Dates and Times with Spring Data JPA
Comparing Objects in Java
Guide to the Volatile Keyword in Java