分析
本题使用动态规划的思想解决。dp[i]
表示:若player从当前位置开始,能获得的最大分数。很明显,需要逆序构建dp
数组。
代码(Python 2.7)
t = int(raw_input())
for t_i in xrange(t):
n = int(raw_input())
a = map(int, raw_input().split())
cum_sum = [0]
for i in xrange(n - 1, -1 , -1):
cum_sum.append(a[i] + cum_sum[-1])
cum_sum.reverse()
cum_sum.pop()
if n < 4:
print cum_sum[0]
# Reverse DP: O(n).
dp = [0] * n
dp[-1] = a[-1]
dp[-2] = dp[-1] + a[-2]
dp[-3] = dp[-2] + a[-3]
for index in xrange(n - 4, -1, -1):
# If current player remove 1 brick from current state.
v1 = a[index] + cum_sum[index + 1] - dp[index + 1]
# If current player remove 2 bricks from current state.
v2 = a[index] + a[index + 1] + cum_sum[index + 2] - dp[index + 2]
# If current player remove 3 bricks from current state.
v3 = a[index] + a[index + 1] + a[index + 2] + cum_sum[index + 3] - dp[index + 3]
dp[index] = max([v1, v2, v3])
print dp[0]