Created
May 5, 2019 15:13
-
-
Save Edgar-P-yan/a833c1af22bf50965325d7dd57b5fb7d to your computer and use it in GitHub Desktop.
Contiguous array with the same degree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function alg(arr) { | |
const maxFreqNum = findMaxFreqNum(arr) | |
const firstIndex = arr.indexOf(maxFreqNum) | |
const lastIndex = arr.lastIndexOf(maxFreqNum) | |
const contiguousArr = arr.slice(firstIndex, lastIndex+1) | |
return contiguousArr.length | |
} | |
function findMaxFreqNum(arr) { | |
const nums = {}; | |
arr.forEach(el => { | |
if(!(el in nums)) { | |
nums[el] = 0 | |
} | |
nums[el] += 1 | |
}) | |
let maxFreqNum = -1; | |
let maxFreq = -1; | |
Object.entries(nums).forEach(([n, freq]) => { | |
if(freq > maxFreq) { | |
maxFreq = freq | |
maxFreqNum = n | |
} | |
}) | |
return +maxFreqNum // Keys of Objects are Strings, converting to Number | |
} | |
function parseInput(data) { | |
const [lengthStr, arrayStr] = data.split('\n') | |
const array = arrayStr.split(' ').map(n => parseInt(n, 10)) | |
return array | |
} | |
// Testing | |
console.log(alg([1,2,5,6,1])) | |
console.log(alg([1,1,1,2,3])) | |
console.log(alg([1,2,3,4,4,4,5,6])) | |
console.log(alg([1,2,3,4,4,0,0,4,5,6])) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment