Max double slice sum

前端 未结 14 1201
后悔当初
后悔当初 2020-12-13 20:53

Recently, I tried to solve the Max Double Slice Sum problem in codility which is a variant of max slice problem. My Solution was to look for a slice that has maximum value w

14条回答
  •  甜味超标
    2020-12-13 20:54

    The most clear Python solution among others:

    def solution(A):
        mid = 1
        total = 0
        max_slice = 0
    
        for idx, end in enumerate(A[2:-1], start=2):
    
            if total < 0:
                mid = idx
                total = 0
    
            elif total == 0 and A[idx - 1] > A[mid]:
                mid = idx - 1
                total = end
    
            else:
                if A[mid] > end:
                    total += A[mid]
                    mid = idx
                else:
                    total += end
    
            max_slice = max(max_slice, total)
    
        return max_slice
    

提交回复
热议问题