Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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]));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement