Short Java solution using two pointers


  • 0
    Y
    public class Solution {
        public int findLHS(int[] nums) {
            Arrays.sort(nums);
    
            int result = 0;
            int left = 0, right = 0;
    
            while (right < nums.length) {
                if (nums[right] - nums[left] < 1)
                    right++;
                else if (nums[right] - nums[left] == 1) {
                    result = Math.max(result, right - left + 1);
                    right++;
                } else
                    left++;
            }
    
            return result;
        }
    }
    

Log in to reply
 

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