
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program for Longest Increasing Subsequence
In this program, we find the length of the longest increasing subsequence (LIS) in an integer array using Java programming language. An increasing subsequence is a sequence of numbers where each number is greater than the previous one. The program uses a dynamic programming approach to compute the longest increasing subsequence efficiently. This technique involves building a solution using previously computed results.
Problem Statement
Write a Java program to get the length of the longest increasing subsequence ?
Input
10, 22, 9, 33, 21, 50, 41, 60
Output
The length of the longest increasing subsequence is 5
Steps get the length of longest increasing subsequence
Following are the steps to get the length of longest increasing subsequence ?
- Initialize a seq_arr array to store the longest increasing subsequence lengths for each position.
- Update the seq_arr values based on comparisons between array elements.
- Find the maximum value in seq_arr to determine the longest increasing subsequence length.
- Return the maximum value as the length of the longest increasing subsequence.
Java program for longest increasing subsequence
Below is the Java program for the longest increasing subsequence ?
public class Demo{ static int incre_subseq(int my_arr[], int arr_len){ int seq_arr[] = new int[arr_len]; int i, j, max = 0; for (i = 0; i < arr_len; i++) seq_arr[i] = 1; for (i = 1; i < arr_len; i++) for (j = 0; j < i; j++) if (my_arr[i] > my_arr[j] && seq_arr[i] < seq_arr[j] + 1) seq_arr[i] = seq_arr[j] + 1; for (i = 0; i < arr_len; i++) if (max < seq_arr[i]) max = seq_arr[i]; return max; } public static void main(String args[]){ int my_arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; int arr_len = my_arr.length; System.out.println("The length of the longest increasing subsequence is " + incre_subseq(my_arr, arr_len)); } }
Output
The length of the longest increasing subsequence is 5
Code Explanation
In the above Java code, the class named Demo contains a static function named incre_subseq that takes the array and the length of the array as parameters. Inside this function, a new array is created that is empty. A max variable is assigned the value 0. A for loop iterates over the length of the array and every element is initialized to 1. Again, a for loop is iterated, and another for loop is initiated that checks if the first element in the array is equal to the second element and if the array (seq_arr, that had all 1s initialized) has the first element lesser than the second element + 1. The maximum of the elements in the seq_arr is found and returned.