Created
October 28, 2024 09:02
-
-
Save sAVItar02/901434c8763cb1f136a879a3b54fbe23 to your computer and use it in GitHub Desktop.
Best time to buy and sell stocks
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
/** | |
* @param {number[]} prices | |
* @return {number} | |
*/ | |
var maxProfit = function(prices) { | |
let max = 0; | |
let buy = prices[0]; | |
for(let i=0; i<prices.length; i++) { | |
if(prices[i] > buy) max = Math.max(max, prices[i] - buy); | |
else buy = prices[i]; | |
} | |
return max; | |
}; | |
// loop through the array and check if the current price is more than the buy price | |
// then check if current price - buy price is greater than max, if yes then update max | |
// if current price is lesser than the buy price, then make the current price the buy price |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment