The max product of consecutive elements in an array

后端 未结 8 1595
面向向阳花
面向向阳花 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:15

    Using python notations:

    • compute min( prod( v[ 0: ] ), prod( v[ 1: ] ), ..., prod( v[ -1 ] ) ) and max( prod( v[ 0: ] ), prod( v[ 1: ] ), ..., prod( v[ -1 ] ) ) in O(n)
    • compute recursively the max product based on the fact that maxpro(v) = max( maxpro(v[:-1]) * max( prod( v[ 0: ] ), prod( v[ 1: ] ), ..., prod( v[ -1 ] ) ). This is O(n) too

    Here is the code:

    #
    n = 5
    vmax = 10
    
    #
    v = nr.randint( 1, vmax, n )
    v *= nr.randint( 0, 2, n ) * 2 - 1
    #
    print v
    
    #
    prod_res = np.zeros( ( 2, n ), int )
    prod_res[ 0, 0 ] = prod_res[ 1, 0 ] = v[ 0 ]
    for i in xrange( 1, n ) :
        prod_res[ 0, i ] = min( v[ i ], prod_res[ 1, i-1 ] * v[ i ], prod_res[ 0, i-1 ] * v[ i ] )
        prod_res[ 1, i ] = max( v[ i ], prod_res[ 1, i-1 ] * v[ i ], prod_res[ 0, i-1 ] * v[ i ] )
    #
    print prod_res
    
    #
    def maxpro_naive( v ) :
        return v[ 0 ] if ( len( v ) == 1 ) else max( maxpro_naive( v[ :-1 ] ), prod_res[ 1, len(v) -1 ] )
    #
    print maxpro_naive( v )
    

提交回复
热议问题