Skip to content

Instantly share code, notes, and snippets.

@theabbie
Created December 30, 2021 10:38
Show Gist options
  • Select an option

  • Save theabbie/a09a38bc192e2791fd688427687f9b1e to your computer and use it in GitHub Desktop.

Select an option

Save theabbie/a09a38bc192e2791fd688427687f9b1e to your computer and use it in GitHub Desktop.
Best time to buy and sell stocks leetcode slow solution
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