Java LeetCode 300. The longest increasing subsequence

Give you an integer array nums and find the length of the longest strictly increasing subsequence.
A subsequence is a sequence derived from an array, deleting (or not deleting) elements in the array without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
Example 1:
Input: nums = [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], so the length is 4.

Dynamic programming
Traverse the array and store the maximum length of each element in the dp array. The maximum length of the last position dp[i] is less than the maximum length of the element before +1

class Solution {
    
    
    public int lengthOfLIS(int[] nums) {
    
    
        int dp[] = new int[nums.length];

        Arrays.fill(dp,1);
        int max=1;

        for(int i=1;i<nums.length;i++){
    
    
            for(int j=0;j<i;j++){
    
    
                if(nums[j]<nums[i]){
    
    
                    dp[i] = Math.max(dp[i],dp[j]+1);
                }
            }
            max = Math.max(max,dp[i]);
        }

        return max;
    }
}

Guess you like

Origin blog.csdn.net/sakura_wmh/article/details/111242486