Skip to content

Instantly share code, notes, and snippets.

@priyankvex
Created August 16, 2019 10:18
Show Gist options
  • Save priyankvex/2fa97c1a8bd369b71d4044128394ea5a to your computer and use it in GitHub Desktop.
Save priyankvex/2fa97c1a8bd369b71d4044128394ea5a to your computer and use it in GitHub Desktop.
Minimum number of candies needed for distribution
class Solution(object):
def solve(self, a):
candies = [1 for i in a]
n = len(a)
# first pass
for i in range(1, n):
if a[i] > a[i-1]:
candies[i] = candies[i-1] + 1
# second pass
for i in range(n-2, -1, -1):
if a[i] > a[i+1]:
candies[i] = max(candies[i+1] + 1, candies[i])
return sum(candies)
if __name__ == "__main__":
a = [5, 5, 4, 3, 2, 1]
ans = Solution().solve(a)
print(ans)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment