Last active
December 5, 2022 21:13
-
-
Save kidCaulfield/254ba2933ad5181a0e6ec0c9cf261404 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// calcuale the greatest profit | |
function evaluate() { | |
// store greatest profit | |
let evaluation = -1; | |
// calculate position | |
return function (min, max) { | |
const profit = max - min; | |
evaluation = evaluation < profit ? profit : evaluation; | |
return evaluation; | |
}; | |
} | |
// Find maximum profit | |
function maximumProfit(arr) { | |
// declare min node, evaution function and result | |
let min = arr[0], | |
profit = -1; | |
const evaluation = evaluate(); | |
for (let i = 1; i < arr.length; i++) { | |
// when the current position is greater than min value | |
if (arr[i] > min) { | |
// calculate profit | |
profit = evaluation(min, arr[i]); | |
} | |
// only set min if less then previous position | |
if (arr[i] < min) { | |
min = arr[i]; | |
} | |
} | |
return profit; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Code from a recent challenge.