[Java] clean and easy to understand solution


  • 0
    S

    I know it is an easy question, but just want to have a taste of sharing solution :0

    In the for loop, I choose to start from index 1 rather than 0, since except for edge cases, the length should be at least 1.

    class Solution {
        public int findLengthOfLCIS(int[] nums) {
            if(nums.length < 2) return nums.length; // edge cases  
            int maxLen = 1, curLen = 1;   // ** length is at least 1
            for(int i = 1; i < nums.length; i++){
                if(nums[i] > nums[i-1]){
                    curLen++;
                    maxLen = Math.max(maxLen, curLen);
                }else curLen = 1;        // ** length is at least 1
            }
            return maxLen;
        }
    }
    

    Time: O(n)
    Space: O(1)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.