Skip to content

Instantly share code, notes, and snippets.

@junjiah
Last active August 27, 2015 08:46
Show Gist options
  • Save junjiah/0e865ef0dcdfefa461a8 to your computer and use it in GitHub Desktop.
Save junjiah/0e865ef0dcdfefa461a8 to your computer and use it in GitHub Desktop.
solved 'Candies' on hackerrank https://www.hackerrank.com/challenges/candies
import sys
def find_min_candies(ratings):
"""ratings: A list of ratings"""
sz = len(ratings)
# Records number of continuous elements less than
# the current rating from left and right.
less_from_left, less_from_right = [0] * sz, [0] * sz
for i in range(1, sz):
if ratings[i - 1] < ratings[i]:
less_from_left[i] = less_from_left[i - 1] + 1
if ratings[-i] < ratings[-i - 1]:
less_from_right[-i - 1] = less_from_right[-i] + 1
# The number of candies is bounded by the greater of
# the corresponding element in above arrays.
min_candies = sum(
max(pair) + 1 for pair in zip(less_from_left, less_from_right))
return min_candies
if __name__ == '__main__':
raw_input()
ratings = map(int, sys.stdin.readlines())
print find_min_candies(ratings)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment