Java Program for Longest Increasing Subsequence

JavaObject Oriented ProgrammingProgramming

Following is the Java program for longest increasing subsequence −

Example

 Live Demo

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

A 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, 'for' loop is iterated, and another 'for' loop is initiated that checks if first element in the array is equal to the second element and if the array (seq_arr, that had all 1s initialized) has first element lesser than the second element + 1. The maximum of the elements in the seq_arr is found and returned. This is dynamic programming technique wherein one value is computed and stored in an array, removing the need to compute it again and again as in recursion. Whenever a previously computed element is required, it is fetched from the array.

raja
Published on 07-Jul-2020 07:37:44
Advertisements