Longest Increasing Subsequence

Medium
dynamic-programming

Given an integer array nums, return the length of the longest strictly increasing subsequence.

A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements.

Recurrence Relation: dp[i] = max(dp[j] + 1) for all j < i where nums[j] < nums[i]

For each element, we look at all previous elements that are smaller and extend the longest subsequence ending at that element.

Optimization: This can be solved in O(n log n) using binary search with a patience sorting approach, but the O(n^2) DP solution is the foundation.

Example 1

Input: nums = [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101] or [2,3,7,18], therefore the length is 4.

Example 2

Input: nums = [0,1,0,3,2,3]
Output: 4
Explanation: The longest increasing subsequence is [0,1,2,3].

Example 3

Input: nums = [7,7,7,7,7,7,7]
Output: 1
Explanation: All elements are the same, so the longest strictly increasing subsequence has length 1.

Constraints

  • 1 <= nums.length <= 2500
  • -10^4 <= nums[i] <= 10^4
Show Hints (4)
Hint 1: dp[i] represents the length of the longest increasing subsequence ending at index i.
Hint 2: For each element, look at all previous elements.
Hint 3: If nums[j] < nums[i], we can extend the subsequence ending at j.
Hint 4: The answer is the maximum value in the dp array.
Loading editor...

Test Results

Click "Run" to execute your code against test cases

AI Tutor

Socratic guidance - I'll ask questions, not give answers

AI Tutor
Hello! I'm your AI tutor, here to guide you through this problem using the Socratic method. I won't give you direct answers, but I'll ask questions and provide hints to help you discover the solution yourself. What's your first instinct when you look at this problem? What approach comes to mind?