Implement the longestIncreasingSubsequenceLength method that returns the length of the longest strictly increasing subsequence.

The input contains an integer array nums and its length size. Your task is to find the length of the longest increasing subsequence.

A subsequence is created by taking elements in the same order, but not necessarily from consecutive positions. The selected values must be strictly increasing. For example, in [10,9,2,5,3,7,101,18], one valid longest increasing subsequence is [2,3,7,101], so the answer is 4.

Example 1

Input
nums (int[]) = [10,9,2,5,3,7,101,18]
size (int) = 8
Returns (int) 4

Example 2

Input
nums (int[]) = [0,1,0,3,2,3]
size (int) = 6
Returns (int) 4

Example 3

Input
nums (int[]) = [7,7,7]
size (int) = 3
Returns (int) 1

Use dynamic programming where dp[i] means the length of the longest increasing subsequence ending at index i.

Every element alone has length 1. For each index i, check all previous indexes j. If nums[j] is smaller than nums[i], then nums[i] can extend the subsequence ending at j.

The answer is the maximum value stored in the dp array.

Pseudocode:

function longestIncreasingSubsequenceLength(nums, size):
    if size == 0:
        return 0
    dp = array of size values filled with 1
    answer = 1
    for i from 0 to size - 1:
        for j from 0 to i - 1:
            if nums[j] < nums[i]:
                dp[i] = max(dp[i], dp[j] + 1)
        answer = max(answer, dp[i])
    return answer
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.