mediumStackPattern: Monotonic Stack

Max Increasing Subsequence Length Solution

Problem Statement

Given an array of integers, find the length of the longest subsequence where the values are strictly increasing.

Examples

Example 1:
Input:[-1,3,5,4,7],
Output:4
Explanation: Explanation of increasing subsequence.
Example 2:
Input:[1,2,3,4,5]
Output:5
Explanation: Each number is greater than its previous.
Example 3:
Input:[-5, 2, 6, 7, 9, 12]
Output:6
Explanation: Every number is greater than the previous one.

Constraints

  • Length of the input array can be up to 10^5
  • All numbers in the input array are integers
  • Input array can contain negative numbers
  • Input array can be empty
  • Input array contains numbers that are strictly increasing
Time: O(n^2) Space: O(n)
We can solve this problem using a dynamic programming approach by maintaining an array where each element stores the number of strictly increasing elements ending at the current index.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

def max_increasing_subsequence(input): dp = [0]*len(input) maxIncreasingSubsequence = 0 for num in input: for i in range(len(dp)): if num > dp[i]: if i == len(dp)-1: dp.append(num) else: dp[i] = num maxIncreasingSubsequence = max(maxIncreasingSubsequence, max(dp)) return maxIncreasingSubsequence