循环数组,两数相加最大且两数不能相邻的情况,在O(n)情况下完成:
想了很久,海总想出了递推公式:
譬如 a = [4,1,2,4] max = 6
class Solution:
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = nums
l = len(a)
if l==0:
return 0
if l<3:
return max(a)
if l==3:
return a[1]
m1=0
m2=2
max1 = a[m1]+a[m2]
for i in range(l):
if i>=3:
nbs = [m1-1,m1,m1+1,m2-1,m2,m2+1]
max2 = 0
for j in nbs:
if j<=i and j>=0 and j!=i-1 and j!= i-1 and j!=i and j!=0:
max_temp = a[i] + a[j]
if max_temp > max2:
max2 = max_temp
m1_t = i
m2_t = j
if max2>max1:
max1 = max2
return max1