Given an integer array nums, find the longest run of numbers you can pick, left to right, with each one bigger than the one before, and return how many it has. The picked numbers don't have to sit next to each other, and an equal number doesn't count as bigger.
Examples
Example 1:
Input: nums = [10,9,2,5,3,7,101,18]
Output: 4
Explanation: [2,3,7,101] (or [2,5,7,101]).
Example 2:
Input: nums = [0,1,0,3,2,3]
Output: 4
Example 3:
Input: nums = [7,7,7,7]
Output: 1
Example 4:
Input: nums = [4,10,4,3,8,9]
Output: 3
Constraints
1 <= nums.length <= 2500
-10^4 <= nums[i] <= 10^4
Prerequisites
Dynamic programming — being able to say, in one sentence, what a single cell of your table MEANS. Everything else follows from that sentence. Rolling variables: when a state only looks back one or two steps, the table collapses to a couple of numbers.
How to think about it
1. Extend the Longest Run Ending on a Smaller Number Optimal
Intuition
Give every number a best: the length of the longest increasing run that ends right on it. A run that ends on a number is a shorter run that ends on a smaller number to its left, with this number added, so a number's best is one more than the best of the smaller numbers before it, or 1 when there is none: the number alone. Fill the bests in from left to right, so each number only looks back at bests already filled. An equal number does not count, because each picked number has to be bigger than the one before it. The answer is the biggest best of all, kept as the bests are filled in, and not the last one: the longest run does not have to end on the last number. On [4, 2, 5, 2, 6, 3] the bests are 1, 1, 2, 1, 3, 2: the answer is 3, the run 4, 5, 6 that ends on the 6, and the last best is only 2. Each number extends the longest subsequence that ends on a smaller number.
Algorithm
1. Give every number a best of 1: on its own, it is a run of one. 2. For each number, look back at every number before it. 3. If that number is smaller, this one can extend its run: its best becomes the bigger of what it has and that number's best plus 1. 4. Keep the biggest best seen so far, and return it after the last number.
Time & Space
Time O(n^2): each of the n numbers looks back at every number before it. Space O(n): one best for every number.
2. Longest Ending Here Optimal
Intuition
best[i] means "the longest increasing subsequence that ENDS at i" — anchoring the definition at an endpoint is what makes the recurrence work, because any such subsequence is some shorter one ending at a smaller earlier value, extended by i. The answer is the largest of those, not the last.
Algorithm
1. Every position starts at length 1: itself. 2. For each i, look back over every earlier j with a strictly smaller value. 3. Take the best of those and add one. 4. Answer with the largest value in the table.
Time & Space
Time O(n^2). Space O(n). The O(n log n) follow-up keeps the smallest possible tail for each length and binary-searches where each value lands.