Share my 5ms DP solution in JAVA, which beats 96% submissions


  • 0
    N
    public int longestConsecutive(int[] nums) { 
            int[] dp = new int[nums.length];
            Arrays.sort(nums);
            Arrays.fill(dp,1);
            int max = 1;
            for (int i=1; i<nums.length; i++){
                if (nums[i]==nums[i-1])  dp[i]=dp[i-1];
                if (nums[i]==nums[i-1]+1)  dp[i]=dp[i-1]+1;
                max = Math.max(dp[i],max);
            }
            return nums.length==0 ? 0 : max;
        }
    

Log in to reply
 

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