The "longest continuous increasing sequence" of the dynamic programming series

674. Longest consecutive increasing sequence

Given an 未经排序integer array, find the longest and 连续increasing sequence, and return that sequence 长度.

Example 1:

输入: [1,3,5,4,7]
输出: 3
解释: 最长连续递增序列是 [1,3,5], 长度为3。
尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为5和7在原数组里被4隔开。 

Example 2:

输入: [2,2,2,2,2]
输出: 1
解释: 最长连续递增序列是 [2], 长度为1。

Note: The length of the array will not exceed 10,000.

Ideas: continuous up, so only consider nums[i]and its front nums[i-1]can

Solution one :

class Solution {
    
    
    public int findLengthOfLCIS(int[] nums) {
    
    
        int LEN = nums.length;
        if(LEN == 0 || nums == null) return 0;
        int[] dp = new int[LEN];
      	Arrays.fill(dp, 1);
        int res = 0;
      	for(int i = 1; i < LEN; i++){
    
    	
            if(nums[i-1] < nums[i]){
    
    
                dp[i] = dp[i-1]+1;
            }
            res = Math.max(res, dp[i]);
        }
      	return (res > 1)? res:1;
    }
}

Time complexity: O(n)

Space compression: O(n)

Solution 2 : Sliding window (state compression), only need to save the previous state, not all states

class Solution {
    
    
    public int findLengthOfLCIS(int[] nums) {
    
    
        int LEN = nums.length;
        if(LEN == 0 || nums == null) return 0;
      
        int pre = 1;
      	int cur = 1;
        int res = 0;
      	for(int i = 1; i < LEN; i++){
    
    	
          	pre = cur;
            if(nums[i-1] < nums[i]){
    
    
                cur = pre + 1;
            }else{
    
    
              	cur = 1;
            }
            res = Math.max(res, cur);
        }
      	
      	return (res > 1)? res:1;
    }
}

Time complexity: O(n)

Space compression: O(1)

Guess you like

Origin blog.csdn.net/weixin_44471490/article/details/109075610