본문 바로가기
Problem Solving/LeetCode

[LeetCode] 594. Longest Harmonious Subsequence - Java

by graycode 2026. 9. 8.

• 문제 링크

 

Longest Harmonious Subsequence - LeetCode

Can you solve this real interview question? Longest Harmonious Subsequence - We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1. Given an integer array nums, return the length of its l

leetcode.com

 

• 풀이 코드

import java.util.HashMap;
import java.util.Map;

public class Solution {

    public int findLHS(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i : nums) map.put(i, map.getOrDefault(i, 0) + 1);

        int max = 0;
        for (int i : map.keySet()) if (map.containsKey(i + 1)) max = Math.max(max, map.get(i) + map.get(i + 1));

        return max;
    }

}

댓글