Advertisement
Guest User

Untitled

a guest
May 25th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.60 KB | None | 0 0
  1. // Find the length of the longest monotonically increasing or monitonically
  2. // decreasing sequence of values in an array.
  3.  
  4. function longest_run(a) {
  5. const less = (a, b) => a < b;
  6. const more = (a, b) => a > b;
  7. const cum = (a, f) => a.map((v, i) => f(v, a[i-1])); // compare adjacent elements
  8. const sum = (a, t = 0) => a.map(v => t = v ? t + v : 0); // running sum, reset on zero
  9.  
  10. return !a.length ? 0 :
  11. 1 + Math.max(...sum(cum(a, less)), ...sum(cum(a, more)));
  12. }
  13.  
  14. console.log(longest_run([1,2,3,4,3,2,1, 0, 2,1, 3,4]));
  15. console.log(longest_run([]));
  16. console.log(longest_run([1]));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement