CodeBlanks Logo Icon CodeBlanks

Challenge 2

Compute and print the LCS length.

Challenge 2: LIS

In this challenge you will solve the longest increasing subsequence (LIS) problem. You will find the longest increasing subsequence in an array.

Array is [10, 9, 2, 5, 3, 7, 101, 18]. The LIS length is 4. Produce this with DP.

Practice lis_length function

Write lis_length(arr). With DP, find the longest increasing subsequence length for each i. Print 4 with print(lis_length([10, 9, 2, 5, 3, 7, 101, 18])).

Starter code

solution.py
def lis_length(arr):
    # Find LIS length with DP

Sample solution

solution.py
def lis_length(arr):
    # Find LIS length with DP
    dp = [1] * len(arr)
    for i in range(1, len(arr)):
        for j in range(i):
            if arr[i] > arr[j]:
                dp[i] = max(dp[i], dp[j] + 1)
    return max(dp)
print(lis_length([10, 9, 2, 5, 3, 7, 101, 18]))

Expected output

4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 LIS condition

Question
if arr[i] ____ arr[j]: dp[i] = max(dp[i], dp[j] + 1)
Answer
if arr[i] > arr[j]: dp[i] = max(dp[i], dp[j] + 1)

Explanation: > is right.

2 Challenge 2: match the terms

Term Meaning
LIS [2,3,7,101]
length 4
arr 8 elements
dp LIS array

3 What does LIS return?

  • All subsequences
  • Length of longest increasing subsequence Correct answer
  • Shortest subsequence
  • Sorted array

Explanation: LIS returns the length of the longest increasing subsequence.

All lessons in Advanced