Created
January 13, 2014 09:21
-
-
Save ronaldronson/8397022 to your computer and use it in GitHub Desktop.
Find local extremums
This file contains 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
function calculate(input) { | |
"use strict"; | |
var len = input.length, extr, max, min, part; | |
extr = input | |
.reduce(function (pre, val, i, arr) { // find local extremums | |
if ((!i && (val > arr[i + 1])) // check first element | |
|| ((i === len - 1) && (val > arr[i - 1])) // check last element | |
|| ((val > arr[i - 1]) && val > arr[i + 1]) // check rest | |
) { | |
pre.push({ val: val, i: i }); | |
} | |
return pre; | |
}, []) | |
.reduce(function (pre, cur, i) { // find to largest extremums | |
if (!i) { // first elem | |
pre.first = cur; | |
} else if (cur.val > pre.first.val) { // check greatest | |
pre.last = pre.first; | |
pre.first = cur; | |
} else if ((cur.val > pre.last.val) || (-1 === pre.last.i)) { // check second greatest | |
pre.last = cur.val; | |
} | |
return pre; | |
}, { | |
first: {val: null, i: -1}, | |
last: {val: null, i: -1} | |
}); | |
min = Math.min(extr.first.i, extr.last.i); | |
max = Math.max(extr.first.i, extr.last.i); | |
part = input.slice(min + 1, max).reduce(function (pre, cur) { return pre + cur; }, 0); | |
return Math.min(extr.first.val, extr.last.val) * (max - min - 1) - part; | |
} | |
console.log(calculate([2, 1, 1, 3, 4, 2, 3, 1, 2, 2, 4, 6, 5, 3])); // 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment