这道题暴力算法,会超时:
class Solution(object):
def maxScoreSightseeingPair(self, A: 'List[int]') -> int:
n = len(A)
maxsum = 0
for i in range(n):
for j in range(i+1,n):
cursum = A[i] + A[j] + i - j
maxsum = max(maxsum,cursum)
return maxsum
因此,需要使用动态规划解决:
class Solution(object):
def maxScoreSightseeingPair(self, A: 'List[int]') -> int:
n = len(A)
ans = 0
pre = A[0]
for i in range(1,n):
pre = max(pre,A[i-1]+i-1)
ans = max(ans,A[i]+pre-i)
return ans