Skip to content

Instantly share code, notes, and snippets.

@kidCaulfield
Last active December 5, 2022 21:13
Show Gist options
  • Save kidCaulfield/254ba2933ad5181a0e6ec0c9cf261404 to your computer and use it in GitHub Desktop.
Save kidCaulfield/254ba2933ad5181a0e6ec0c9cf261404 to your computer and use it in GitHub Desktop.
// 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;
}
@kidCaulfield
Copy link
Author

Code from a recent challenge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment