Skip to content

Instantly share code, notes, and snippets.

@remi-bruguier
Created June 13, 2020 20:43
Show Gist options
  • Save remi-bruguier/708dd117bd781537bf22ae82f5126829 to your computer and use it in GitHub Desktop.
Save remi-bruguier/708dd117bd781537bf22ae82f5126829 to your computer and use it in GitHub Desktop.
You are given an array. Each element represents the price of a stock on that particular day. Calculate and return the maximum profit you can make from buying and selling that stock only once.
const buy_and_sell = (values:number[]):number => {
let maxProfit = 0;
let minPrice = Number.MAX_SAFE_INTEGER;
for(let val of values){
if(val<minPrice) {
minPrice = val;
}else if(val - minPrice > maxProfit){
maxProfit = val - minPrice;
}
}
return maxProfit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment