Skip to content

Instantly share code, notes, and snippets.

@ewlin
Last active January 24, 2019 17:36
Show Gist options
  • Save ewlin/ca2405a2dc8a6352546bd8ae72235878 to your computer and use it in GitHub Desktop.
Save ewlin/ca2405a2dc8a6352546bd8ae72235878 to your computer and use it in GitHub Desktop.
function solution(A) {
//pit is made up of [startPeak, valley, endPeak]
//set startPeak to first item in array
let startPeak = A[0];
let valley; //lowest point, the dip
let endPeak;
let i = 1;
let deepestDepth = -1;
//find the begining of the pit (if first item in array is not)
while(A[i] > startPeak) {
startPeak = A[i];
i++;
}
//search for pits
for (; i<A.length; i++) {
//if a pit is found, calculate depth
if (startPeak != null && valley != null && endPeak != null) {
console.log([startPeak, valley, endPeak]);
let depth = calculatePitDepth([startPeak, valley, endPeak]);
if (depth > deepestDepth) deepestDepth = depth;
startPeak = endPeak; //the end of the pit is now the start of the next pit
valley = null;
endPeak = null;
}
//otherwise, look for pit
if (A[i] < startPeak && valley == null) {
if (A[i] > A[i+1]) { //not at lowest point yet
continue;
} else if (A[i] < A[i+1]) { //found the local minima
valley = A[i];
}
}
//if we've found the local minima, start looking for the end of the pit
if (valley != null) {
if (i != A.length - 1) {
if (A[i] < A[i+1]) {
continue;
} else if (A[i] > A[i+1]) {
endPeak = A[i];
}
//check last value and see if it goes up or down
} else {
if (A[i] > valley) endPeak = A[i];
}
}
}
if (startPeak != null && valley != null && endPeak != null) {
console.log([startPeak, valley, endPeak]);
let depth = calculatePitDepth([startPeak, valley, endPeak]);
if (depth > deepestDepth) deepestDepth = depth;
}
return deepestDepth;
}
//Calculate depth of a pit: e.g., [0,-5,10] // returns 5
function calculatePitDepth(arr) {
const a = arr[0] - arr[1];
const b = arr[2] - arr[1];
//smaller of the two distances
return Math.min(a,b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment