1148. 最长和谐子序列
我们将一个和谐数组定义为是其最大值和最小值之间的差值恰好为1的数组。
现在,给定一个整数数组,您需要在其所有可能的子序列中找到其最长的和谐子序列的长度。
样例
输入:[1,3,2,2,5,2,3,7]
输出:5
解释:最长的和谐子序列是[3,2,2,2,3]。
注意事项
输入数组的长度不会超过20,000。
public class Solution {
/**
* @param nums: a list of integers
* @return: return a integer
*/
public int findLHS(int[] nums) {
// write your code here
int max = 0;
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int value : nums) {
if (hashMap.containsKey(value)) {
int num = hashMap.get(value);
hashMap.put(value, ++num);
} else {
hashMap.put(value, 1);
}
}
for (Map.Entry<Integer, Integer> entry : hashMap.entrySet()) {
for (Map.Entry<Integer, Integer> entry2 : hashMap.entrySet()) {
if (Math.abs( entry.getKey() - entry2.getKey()) == 1){
max=Math.max(max,entry.getValue()+entry2.getValue());
}
}
}
return max;
}
}