Created
June 13, 2020 20:43
-
-
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.
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 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