Introduction:
In this article, we will explore the Longest Increasing Subsequence (LIS) problem and provide solutions in both Java and Python programming languages. The LIS problem involves finding the length of the longest subsequence of a given array where the elements are in strictly increasing order.
Problem Statement:
Given an array of integers, we need to find the length of the longest increasing subsequence.
Example:
Input: [10, 22, 9, 33, 21, 50, 41, 60, 80]
Output: 6 (The LIS is [10, 22, 33, 50, 60, 80])
Java Solution:
public class LongestIncreasingSubsequence {
public static int lengthOfLIS(int[] nums) {
int n = nums.length;
int[] dp = new int[n];
int maxLen = 1;
for (int i = 0; i < n; i++) {
dp[i] = 1;
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
maxLen = Math.max(maxLen, dp[i]);
}
return maxLen;
}
public static void main(String[] args) {
int[] nums = {10, 22, 9, 33, 21, 50, 41, 60, 80};
System.out.println("Length of LIS: " + lengthOfLIS(nums));
}
}
Python Solution:
def length_of_lis(nums):
n = len(nums)
dp = [1] * n
max_len = 1
for i in range(n):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
max_len = max(max_len, dp[i])
return max_len
if __name__ == "__main__":
nums = [10, 22, 9, 33, 21, 50, 41, 60, 80]
print("Length of LIS:", length_of_lis(nums))
Explanation:
- We use dynamic programming to solve the LIS problem. In both Java and Python solutions, we create a DP array where
dp[i]represents the length of the LIS ending at indexi. - We initialize all elements of the DP array to 1 because the minimum LIS length for any element is 1 (the element itself).
- We iterate through the array and for each element at index
i, we compare it with all elements before it (at indexj). Ifnums[i]is greater thannums[j], it means we can extend the LIS ending atjby includingnums[i]. Thus, we updatedp[i] = dp[j] + 1if it gives a longer LIS fori. - We keep track of the maximum length encountered while iterating and return it as the final result.
Conclusion:
In this article, we discussed the Longest Increasing Subsequence problem and provided solutions in Java and Python. Both solutions use dynamic programming to efficiently find the length of the longest increasing subsequence in the given array. The presented code snippets can be readily used as a starting point to tackle similar problems in real-world scenarios.