Created
August 7, 2023 17:27
-
-
Save ahsanhabibleon/8bc63a7c943202a2f481105424532b81 to your computer and use it in GitHub Desktop.
Ostad cracking coding interview: assignment on array
This file contains hidden or 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
| 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