Skip to content

Instantly share code, notes, and snippets.

@rtm
Created May 25, 2016 07:15
Show Gist options
  • Save rtm/490e9647d196b8bdf774d10e317c99ed to your computer and use it in GitHub Desktop.
Save rtm/490e9647d196b8bdf774d10e317c99ed to your computer and use it in GitHub Desktop.
// 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]));
@hrishikeshs
Copy link

This code is so beautiful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment