Skip to content

Instantly share code, notes, and snippets.

@junjiah
Created August 29, 2015 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save junjiah/2b10ad341e8b5244aca1 to your computer and use it in GitHub Desktop.
Save junjiah/2b10ad341e8b5244aca1 to your computer and use it in GitHub Desktop.
solved 'Bricks Game' on hackerrank https://www.hackerrank.com/challenges/play-game
def max_score(bricks):
"""bricks: A list of bricks."""
sz = len(bricks)
# DP algorithm. See the editorial.
# https://www.hackerrank.com/challenges/play-game/editorial
max_score_from = [0] * sz
max_score_from[-1] = bricks[-1]
max_score_from[-2] = max_score_from[-1] + bricks[-2]
max_score_from[-3] = max_score_from[-2] + bricks[-3]
backward_sum = max_score_from[:]
for i in range(sz - 4, -1, -1):
# Calculate scores with different actions: take 1, 2 or 3 bricks.
score_take_one = bricks[i] + \
backward_sum[i + 1] - max_score_from[i + 1]
score_take_two = bricks[i] + bricks[i + 1] + \
backward_sum[i + 2] - max_score_from[i + 2]
score_take_three = bricks[i] + bricks[i + 1] + bricks[i + 2] + \
backward_sum[i + 3] - max_score_from[i + 3]
max_score_from[i] = max(
score_take_one, score_take_two, score_take_three)
backward_sum[i] = backward_sum[i + 1] + bricks[i]
return max_score_from[0]
test_case_num = int(raw_input())
for _ in range(test_case_num):
raw_input()
bricks = map(int, raw_input().split())
print max_score(bricks)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment