The max product of consecutive elements in an array

后端 未结 8 1504
面向向阳花
面向向阳花 2021-01-30 03:13

I was asked this algorithm question during my onsite interview. Since I was not asked to sign NDA, I post it here for an answer.

Given an array of REAL

8条回答
  •  别那么骄傲
    2021-01-30 04:02

    You can implement a variant of the Kadane algorithm (http://en.wikipedia.org/wiki/Maximum_subarray_problem) who runs with constant extra memory and linear in the size of the problem (no extra array,...)

    If only strict positive numbers are given:

    def max_subarray_mul(A):
        max_ending_here = max_so_far = 1
        for x in A:
            if x > 0
                max_ending_here = max(1,max_ending_here*x)
                max_so_far = max(max_so_far, max_ending_here)
        return max_so_far
    

    I'm still working on the part with negative numbers

    Or a more expensive (in time) method is the following, but this will work with negative numbers:

    def max_subarray_mul(A):
        max_so_far = 1
        n = length(A)
        for i in 1...n:
            x = A[i]
            tmp = x
            max_so_far = max(max_so_far,tmp)
            for j in i+1...n:
              tmp = tmp*A[j]
              max_so_far = max(max_so_far,tmp)
        return max_so_far
    

    Which runs in constant memory and O(n²) time

提交回复
热议问题