Created
December 19, 2018 12:30
-
-
Save malisetti/6e1ed8cf815f9267414758365b3ad274 to your computer and use it in GitHub Desktop.
This file contains 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
"use strict"; | |
const assert = require("assert"); | |
/** | |
* Consider the leftmost and righmost appearances of some value in an array. We'll say that the "span" is the number of elements between the two inclusive. A single value has a span of 1. Returns the largest span found in the given array. (Efficiency is not a priority.) | |
maxSpan([1, 2, 1, 1, 3]) → 4 | |
maxSpan([1, 4, 2, 1, 4, 1, 4]) → 6 | |
maxSpan([1, 4, 2, 1, 4, 4, 4]) → 6 | |
*/ | |
(() => { | |
const inouts = [ | |
{ | |
in: [1, 2, 1, 1, 3], | |
out: 4 | |
}, | |
{ | |
in: [1, 4, 2, 1, 4, 1, 4], | |
out: 6 | |
}, | |
{ | |
in: [1, 4, 2, 1, 4, 4, 4], | |
out: 6 | |
} | |
]; | |
inouts.forEach(e => { | |
assert.equal(e.out, maxSpan(e.in), "fail"); | |
}); | |
})(); | |
function maxSpan(arr) { | |
const spans = {}; | |
let mSpan = 0; | |
for (let i = 0; i < arr.length; i++) { | |
const n = arr[i]; | |
if (!(n in spans)) { | |
spans[n] = i; | |
} else { | |
const span = i - spans[n] + 1; | |
if (span > mSpan) { | |
mSpan = span; | |
} | |
} | |
} | |
return mSpan; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment