
给定一个整数数组,找到任意两个元素之间的绝对差小于或等于
的最长子数组例子
_a = [1,1,2,2,4,4,5,5,5]_
有两个满足条件的子数组:[1,1,2,2]和[4,4,5,5,5]。最大长度子数组有 5 个元素。
功能说明
在下面的编辑器中完成pickingnumbers函数。
pickingnumbers 有以下参数:
- int a[n]:整数数组
退货
- int:满足条件的最长子数组的长度
输入格式
第一行包含一个整数n,即数组a的大小。
第二行包含 n 个空格分隔的整数,每个整数都是 a[i].
解决方案
function pickingNumbers(a) {
// Create an array to store frequency of each element in the input array
let frequency = new Array(100).fill(0);
// Count frequency of each element
for (let i = 0; i < a.length; i++) {
frequency[a[i]]++;
}
// Initialize a variable to store the maximum length of subarray found
let maxLength = 0;
// Traverse through frequency array to find the longest subarray
for (let i = 1; i < frequency.length; i++) {
// The length of a valid subarray is the sum of the frequency of
// the current element and the previous element
maxLength = Math.max(maxLength, frequency[i] + frequency[i - 1]);
}
return maxLength;
}
登录后复制
以上就是选择数字 - HakerRank 解决方案 - Javascript的详细内容,更多请关注php中文网其它相关文章!
www.knlz.cn