32. Longest increasing subsequence
A subsequence is what you get by picking some items from a list and keeping them in their original order. You can
skip items, so the ones you pick don't have to be next to each other: [2, 7, 18] is a subsequence of
[2, 5, 7, 18], but [7, 2] is not.
A subsequence is strictly increasing when each number is bigger than the one before it. An equal number doesn't
count: [2, 2] is not increasing.
Write a function lis_length(numbers) that takes a list of whole numbers and returns the length of its longest
strictly increasing subsequence, as a whole number. You return only how long it is, not the subsequence itself. If
the list is empty, return 0.
Example 1
numbers = [10, 9, 2, 5, 3, 7, 101, 18]4Example 2
numbers = [3, 2, 1]1Example 3
numbers = [1, 3, 3, 4]3Constraints
numbershas 0 to 100 items.- Each item is a whole number from -1000 to 1000. Numbers can repeat.
Submit also runs 5 more tests you can't see.
- Solve it for each position: let
best[i]be the length of the longest increasing subsequence that ends withnumbers[i]. On its own, every number gives 1. - A subsequence ending at an earlier
jcan be extended bynumbers[i]only ifnumbers[j] < numbers[i], strictly smaller, so equal numbers never chain. Thenbest[j] + 1is a candidate forbest[i]. - Two loops: for each
i, try everyjbefore it and keep the biggest candidate. The answer is the biggestbest[i], and 0 for an empty list:max(best, default=0).
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def lis_length(numbers):
"""Length of the longest strictly increasing subsequence.
numbers: list of int; may be empty, may repeat
Returns: int, how many numbers the longest strictly
increasing subsequence has (0 for an empty list)
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.