Log In Sign Up
Day 35

Day 35: Longest Increasing Subsequence

35/60 Days

Longest Increasing Subsequence (LIS) #

Welcome to Day 35 of our 60 Days of Coding Algorithm Challenge! Today, we’ll explore the Longest Increasing Subsequence (LIS) problem, a classic dynamic programming problem with applications in various fields.

What is the Longest Increasing Subsequence? #

The Longest Increasing Subsequence problem is to find a subsequence of a given sequence in which the subsequence’s elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible. This subsequence is not necessarily contiguous or unique.

For example, the LIS of [10, 22, 9, 33, 21, 50, 41, 60, 80] is [10, 22, 33, 50, 60, 80] of length 6.

Naive Recursive Approach #

Let’s start with a naive recursive implementation:

 1def lis_naive(arr):
 2    n = len(arr)
 3    
 4    def lis_helper(i, prev):
 5        if i == n:
 6            return 0
 7        
 8        include = 0
 9        if arr[i] > prev:
10            include = 1 + lis_helper(i + 1, arr[i])
11        
12        exclude = lis_helper(i + 1, prev)
13        
14        return max(include, exclude)
15    
16    return lis_helper(0, float('-inf'))
17
18# …