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