Longest Increasing Subsequence (Dynamic Programming)
require "array" def length_of_lis(nums : Array(Int32)) -> Int32 # Handle edge cases: empty or single-element array if nums.empty? return 0 end if nums.size == 1 return 1 end # dp[i] will store the length of the longest increasing subsequence ending at index i dp = Array(Int32).ne...
This algorithm calculates the length of the longest increasing subsequence (LIS) within a given array of integers. It employs dynamic programming, where `dp[i]` represents the length of the LIS ending at index `i`. The a...
The `length_of_lis` function uses dynamic programming with a time complexity of O(N^2), where N is the number of elements in the input array. This is due to the nested loops iterating through all pairs of elements. The space complexity is O(N) for storing the `dp` array. The base cases for empty or single-element arrays are handled correctly. The core logic relies on the invariant that `dp[i]` stores the maximum length of an increasing subsequence ending at index `i`. For each `i`, it checks all `j < i`; if `nums[i] > nums[j]`, it means `nums[i]` can extend the LIS ending at `j`, so we update `dp[i]` to be the maximum of its current value and `dp[j] + 1`. The final answer is the maximum value found in the `dp` array, representing the overall longest increasing subsequence.
FUNCTION length_of_lis(array nums): IF nums is empty THEN RETURN 0 END IF IF nums has 1 element THEN RETURN 1 END IF CREATE an array dp of same size as nums, initialized with 1s FOR i from 1 to length(nums) - 1: FOR j fr...