KatInterview

Find Maximum Strictly Ascending Subsequence Length

Dynamic ProgrammingAuto-graded · 20 test cases
MediumAuto-gradedDynamic Programmingbinary-searchsubsequencesgreedy

Last updated

Tests dynamic programming optimization using binary search to efficiently compute the longest strictly increasing subsequence in O(n log n) time.

You are given an array of integers. Your task is to determine the length of the longest subsequence where each element is strictly greater than the one before it.

A subsequence is formed by removing zero or more elements from the array while keeping the relative order of the remaining elements unchanged. For instance, [5, 8, 12] is a valid subsequence of [5, 3, 8, 1, 12].

Write a function that returns the length of the longest such strictly ascending subsequence.

Constraints

  • 1 <= nums.length <= 2500
  • -10^4 <= nums[i] <= 10^4
  • Elements in the subsequence must be strictly increasing (no equal consecutive values allowed)

Examples

Example 1

Input: longest_ascending_length([10, 9, 2, 5, 3, 7, 101, 18])

Output: 4

Example 2

Input: longest_ascending_length([0, 1, 0, 3, 2, 3])

Output: 4

Hints

Hint 1

Start by thinking about a dynamic programming solution where you track the best subsequence ending at each position. What's the recurrence relation?

Hint 2

To optimize beyond O(n²), consider maintaining an auxiliary array where each position tracks the smallest possible ending value for subsequences of different lengths.

Hint 3

Since you're looking for positions in a sorted structure, binary search can reduce the time complexity to O(n log n).