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

循环数组,两数相加最大且两数不能相邻的情况,在O(n)情况下完成:
想了很久,海总想出了递推公式:


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
            
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第5章 引用类型(返回首页) 本章内容 使用对象 创建并操作数组 理解基本的JavaScript类型 使用基本类型...
    大学一百阅读 3,281评论 0 4
  • 第一章数和数的运算 一概念 (一)整数 1整数的意义 自然数和0都是整数。 2自然数 我们在数物体的时候,用来表示...
    meychang阅读 2,715评论 0 5
  • 1、用C语言实现一个revert函数,它的功能是将输入的字符串在原串上倒序后返回。 2、用C语言实现函数void ...
    希崽家的小哲阅读 6,398评论 0 12
  • * Always remember to check the quality/availability of th...
    Morphiaaa阅读 750评论 0 0
  • 在C语言中,五种基本数据类型存储空间长度的排列顺序是: A)char B)char=int<=float C)ch...
    夏天再来阅读 3,452评论 0 2