How to find the longest increasing subsequence (LIS) of a sequence of numbers in Java

1 Answer

0 votes
import java.util.Arrays;

public class LongestIncreasingSubsequence {

    public static int longestIncreasingSubsequence(int[] nums) {
        if (nums.length == 0) return 0;

        int[] length = new int[nums.length];
        Arrays.fill(length, 1);

        int maxLength = 1;

        for (int i = 1; i < nums.length; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[i] > nums[j]) {
                    length[i] = Math.max(length[i], length[j] + 1);
                }
            }
            maxLength = Math.max(maxLength, length[i]);
        }

        return maxLength;
    }

    public static void main(String[] args) {
        int[] nums = {4, 5, 1, 10, 3, 9, 18, 19};
        
        System.out.println("Length of LIS: " + longestIncreasingSubsequence(nums));
    }
}



/*
run:

Length of LIS: 5

*/

 



answered Jun 8, 2019 by avibootz
edited Nov 6, 2025 by avibootz
...