Skip to content

Instantly share code, notes, and snippets.

@sAVItar02
Created October 28, 2024 09:02
Show Gist options
  • Save sAVItar02/901434c8763cb1f136a879a3b54fbe23 to your computer and use it in GitHub Desktop.
Save sAVItar02/901434c8763cb1f136a879a3b54fbe23 to your computer and use it in GitHub Desktop.
Best time to buy and sell stocks
/**
* @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