LeetCode 135. Candy

def getLocalMins(self, ratings):
localMins = []
for i in range(len(ratings)):
if i == 0 and ratings[i] <= ratings[i + 1]:
localMins.append(i)
elif i == len(ratings) - 1 and ratings[i] <= ratings[i - 1]:
localMins.append(i)
elif ratings[i] <= ratings[i - 1] and ratings[i] <= ratings[i + 1]:
localMins.append(i)
return localMins
def candy(self, ratings):
if len(ratings) == 1: return 1
localMins = self.getLocalMins(ratings)
candies = [1] * len(ratings)

for localMin in localMins:
for i in reversed(range(localMin)):
if ratings[i] > ratings[i + 1]:
candies[i] = max(candies[i], candies[i + 1] + 1)
else:
break
for i in range(localMin + 1, len(ratings)):
if ratings[i] > ratings[i - 1]:
candies[i] = max(candies[i], candies[i - 1] + 1)
else:
break

return sum(candies)
def candy(self, ratings):
candies = [1] * len(ratings)

for i in range(1, len(ratings)):
if ratings[i] > ratings[i - 1]:
candies[i] = candies[i - 1] + 1

for i in reversed(range(0, len(ratings) - 1)):
if ratings[i] > ratings[i + 1]:
candies[i] = max(candies[i], candies[i + 1] + 1)
return sum(candies)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store