2018-08-12 non-adjacent max two-number sum in loop array

weixin_33816300發表於2018-08-12

迴圈陣列,兩數相加最大且兩數不能相鄰的情況,在O(n)情況下完成:
想了很久,海總想出了遞推公式:


2455186-f2c1479f39c0eaef.jpg
non-adjacent max two-sum in loop array.jpg

譬如 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
            

相關文章