Skip to content

Instantly share code, notes, and snippets.

@ahsanhabibleon
Created August 7, 2023 17:27
Show Gist options
  • Select an option

  • Save ahsanhabibleon/8bc63a7c943202a2f481105424532b81 to your computer and use it in GitHub Desktop.

Select an option

Save ahsanhabibleon/8bc63a7c943202a2f481105424532b81 to your computer and use it in GitHub Desktop.
Ostad cracking coding interview: assignment on array
function findMaxProfit(prices) {
const minPrice = Math.min(...prices)
const nextIndexOfBuyingDay = prices.indexOf(minPrice) === prices.length - 1 ? prices.indexOf(minPrice) : prices.indexOf(minPrice) + 1
if(nextIndexOfBuyingDay === prices.length) {
return 0
}else {
return Math.max(...prices.slice(nextIndexOfBuyingDay, prices.length)) - minPrice
}
}
// Here the time complexity is O(n) since the execution time of Math.min/Math.max varies linearly with the size of the input list,
// space complexity will be O(1) as we've stored constant number of values to memory
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment