Created
December 30, 2021 10:38
-
-
Save theabbie/a09a38bc192e2791fd688427687f9b1e to your computer and use it in GitHub Desktop.
Best time to buy and sell stocks leetcode slow solution
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
| def maxProfit(self, prices): | |
| valIndex = {} | |
| maxProfit = 0 | |
| for i, price in enumerate(prices): | |
| if price not in valIndex: | |
| valIndex[price] = [i, i] | |
| else: | |
| valIndex[price][1] = i | |
| newprices = sorted(valIndex.keys()) | |
| n = len(newprices) | |
| for j in range(n - 1, -1, -1): | |
| end = newprices[j] | |
| if end - newprices[0] <= maxProfit: | |
| break | |
| for i in range(j): | |
| curr = end - newprices[i] | |
| if curr <= maxProfit: | |
| break | |
| if valIndex[end][1] > valIndex[newprices[i]][0]: | |
| maxProfit = max(maxProfit, curr) | |
| return maxProfit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment