1. Description
We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.
Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.
2. Runtime Distribution
3. Submission Details
4. Example
Input: [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].
5. Code
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="Java" active="active"]
public int findLHS(int[] nums) { if (nums == null || nums.length == 0) { return 0; } Mapmap = new HashMap (); for (int i = 0; i < nums.length; i++) { map.put(nums[i], map.getOrDefault(nums[i], 0) + 1); } int result = 0; for (int key : map.keySet()) { if (map.containsKey(key + 1)) { result = Math.max(result, map.get(key + 1) + map.get(key)); } } return result; }
[/restab]
[/restabs]
6.Test
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="Java" active="active" ]
import java.util.HashMap; import java.util.Map; public class LeetCode0594 { public int findLHS(int[] nums) { if (nums == null || nums.length == 0) { return 0; } Mapmap = new HashMap (); for (int i = 0; i < nums.length; i++) { map.put(nums[i], map.getOrDefault(nums[i], 0) + 1); } int result = 0; for (int key : map.keySet()) { if (map.containsKey(key + 1)) { result = Math.max(result, map.get(key + 1) + map.get(key)); } } return result; } public static void main(String[] args) { LeetCode0594 leetcode = new LeetCode0594(); System.out.println(leetcode.findLHS(new int[] { 1, 3, 2, 2, 5, 2, 3, 7 })); } }
[/restab]
[/restabs]
Comments | NOTHING