Skip to content

Instantly share code, notes, and snippets.

@zekhoi
Created May 3, 2022 10:49
Show Gist options
  • Save zekhoi/2e2eac6daf0398b883afdb9e66eb08b7 to your computer and use it in GitHub Desktop.
Save zekhoi/2e2eac6daf0398b883afdb9e66eb08b7 to your computer and use it in GitHub Desktop.
Coderbyte Stock Maximum Profit
function ArrayChallenge(arr) {
// Declare variables
let buy_price = 0
let sell_price = 0
let max_profit = -1
let next_buy_price = true
// Loop every price and calculate it
// console.log(arr)
for(let i = 0; i < arr.length; i++){
for(let j = i; j < arr.length; j++){
buy_price = arr[j]
sell_price = arr[i]
let difference = buy_price-sell_price
// console.log(arr[j],"-",arr[i],"=",difference)
// Set condition if buy - sell higher than current max profit
if(difference > max_profit){
max_profit = difference
// console.log(max_profit)
}
}
}
// Set final max profit
let fixprofit = max_profit > 0 ? max_profit : -1
return fixprofit;
}
// keep this function call here
console.log(ArrayChallenge(readline()));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment