首页  >  文章  >  web前端  >  选择数字 - HakerRank 解决方案 - Javascript

选择数字 - HakerRank 解决方案 - Javascript

WBOY
WBOY原创
2024-09-03 11:33:47255浏览

Picking Numbers - HakerRank Solution - Javascript

给定一个整数数组,找到任意两个元素之间的绝对差小于或等于

的最长子数组

例子

_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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn