Created
May 25, 2016 07:15
-
-
Save rtm/490e9647d196b8bdf774d10e317c99ed to your computer and use it in GitHub Desktop.
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
// Find the length of the longest monotonically increasing or monitonically | |
// decreasing sequence of values in an array. | |
function longest_run(a) { | |
const less = (a, b) => a < b; | |
const more = (a, b) => a > b; | |
const cum = (a, f) => a.map((v, i) => f(v, a[i-1])); // compare adjacent elements | |
const sum = (a, t = 0) => a.map(v => t = v ? t + v : 0); // running sum, reset on zero | |
return !a.length ? 0 : | |
1 + Math.max(...sum(cum(a, less)), ...sum(cum(a, more))); | |
} | |
console.log(longest_run([1,2,3,4,3,2,1, 0, 2,1, 3,4])); | |
console.log(longest_run([])); | |
console.log(longest_run([1])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code is so beautiful!