leetcode1014

这道题暴力算法,会超时:

 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

参考:https://leetcode.com/problems/best-sightseeing-pair/discuss/261041/easy-understand-one-pass-answer-by

上一篇:PHP 求两个日期之间相差的天数、月数


下一篇:计算两个日期之间相差的年数月数天数(JS实现)