Max double slice sum

前端 未结 14 1208
后悔当初
后悔当初 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 21:08

    Here is my solution https://github.com/dinkar1708/coding_interview/blob/master/codility/max_slice_problem_max_double_slice_sum.py

    Codility 100% in Python

    def solution(A):
    """
    Idea is use two temporary array and store sum using Kadane’s algorithm
    ending_here_sum[i] -  the maximum sum contiguous sub sequence ending at index i
    starting_here_sum[i] - the maximum sum contiguous sub sequence starting with index i
    
    Double slice sum should be the maximum sum of ending_here_sum[i-1]+starting_here_sum[i+1]
    
    Reference -
    https://rafal.io/posts/codility-max-double-slice-sum.html
    
    The sum of double slice (X, Y, Z) is the total of A[X + 1] + A[X + 2] + ... + A[Y - 1] + A[Y + 1] + A[Y + 2] + ... + A[Z - 1].
    A[0] = 3
    A[1] = 2
    A[2] = 6
    A[3] = -1
    A[4] = 4
    A[5] = 5
    A[6] = -1
    A[7] = 2
    contains the following example double slices:
    double slice (0, 3, 6), sum is 2 + 6 + 4 + 5 = 17,
    double slice (0, 3, 7), sum is 2 + 6 + 4 + 5 - 1 = 16,
    double slice (3, 4, 5), sum is 0.
    """
    ar_len = len(A)
    ending_here_sum = [0] * ar_len
    starting_here_sum = [0] * ar_len
    
    # the maximum sum contiguous sub sequence ending at index i
    for index in range(1, ar_len - 2):  # A[X + 1] + A[X + 2] + ... + A[Y - 1]
        ending_here_sum[index] = max(ending_here_sum[index - 1] + A[index], 0)
    
    # the maximum sum contiguous sub sequence starting with index i
    for index in range(ar_len - 2, 1, -1):  # A[Y + 1] + A[Y + 2] + ... + A[Z - 1]
        starting_here_sum[index] = max(starting_here_sum[index + 1] + A[index], 0)
    
    # Double slice sum should be the maximum sum of ending_here_sum[i-1]+starting_here_sum[i+1]
    max_slice_sum = ending_here_sum[0] + starting_here_sum[2]
    for index in range(1, ar_len - 1):
        max_slice_sum = max(max_slice_sum, ending_here_sum[index - 1] + starting_here_sum[index + 1])
    
    return max_slice_sum
    

提交回复
热议问题