Last active
August 1, 2019 20:57
-
-
Save MunifTanjim/b8b00da1a394849e41fabd8b8d86d213 to your computer and use it in GitHub Desktop.
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
const testArr = [ | |
/* 0 */ 0, | |
/* 1 */ 1, | |
/* 2 */ 0, | |
/* 3 */ -3, | |
/* 4 */ 1, | |
/* 5 */ 3, | |
/* 6 */ 4, | |
/* 7 */ 0, | |
/* 8 */ 1, | |
/* 9 */ 3, | |
/* 10 */ -2, | |
/* 11 */ 0 | |
] | |
function calculatePits(arr) { | |
const pits = [] | |
for (let p = 0; p < arr.length; p++) { | |
const pVal = arr[p] | |
let qComp = pVal | |
for (let q = p + 1; q < arr.length; q++) { | |
const qVal = arr[q] | |
if (qVal < qComp) { | |
let rComp = qVal | |
for (let r = q + 1; r < arr.length; r++) { | |
const rVal = arr[r] | |
if (rVal > rComp) { | |
pits.push([p, q, r]) | |
rComp = rVal | |
} else { | |
break | |
} | |
} | |
qComp = qVal | |
} else { | |
break | |
} | |
} | |
} | |
checkPits(pits, arr) | |
return pits | |
} | |
function checkPits(pits, arr) { | |
pits.forEach(([p, q, r]) => { | |
for (let i = p; i <= q - 1; i++) { | |
if (arr[i] < arr[i + 1]) { | |
throw [p, q, r] | |
} | |
} | |
for (let i = q; i <= r - 1; i++) { | |
if (arr[i] > arr[i + 1]) { | |
throw [p, q, r] | |
} | |
} | |
}) | |
} | |
function calculateDepths(pits, arr) { | |
return pits.map(([p, q, r]) => Math.min(arr[p] - arr[q], arr[r] - arr[q])) | |
} | |
function maxPitDepth(arr) { | |
const pits = calculatePits(arr) | |
const depths = calculateDepths(pits, arr) | |
return Math.max(...depths) | |
} | |
console.log(maxPitDepth(testArr)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment