top | item 26749188

Algorithmic Puzzle: Continuous Increasing Subsequences

1 points| bor0 | 4 years ago |bor0.wordpress.com

1 comment

order

cousin_it|4 years ago

It's much simpler, if there's an increasing run of length k, it contains k(k+1)/2 subruns. So you can just do one pass over the array, keeping track of the length of the current run.

    function f(arr) {
      var j=0, ret=0;
      for (var i=1; i<=arr.length; i++) {
        if (i==arr.length || arr[i]<=arr[i-1]) {
          ret += (i-j)*(i-j+1)/2;
          j = i;
        }
      }
      return ret;
    }