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
I wrote below code, for finding maximum product of adjacent integer values in input array, assuming the product would also be in the int range it would iterate the loop n/2 times only
int adjacentElementsProduct(int[] inputArray) {
int maxProdct=inputArray[0]*inputArray[1];
//as we have already taken product of first two , start from 3rd and iterate till second last because we are checking the product of i+1 for every i
for (int i=2; i<inputArray.length-1; i=i+2){
if(inputArray[i-1]*inputArray[i] >inputArray[i]*inputArray[i+1]){
if(inputArray[i-1]*inputArray[i]>maxProdct)
maxProdct =inputArray[i-1]*inputArray[i];
}
else if(inputArray[i+1]*inputArray[i] > maxProdct)
maxProdct=inputArray[i+1]*inputArray[i];
}
//if its an even array the last element would have been covered while calculating product with second last, otherwise we would check the product for last and second last element and compare with maxProduct
if(inputArray.length%2 !=0){
if(maxProdct<inputArray[inputArray.length-1]*inputArray[inputArray.length-2]){
maxProdct=inputArray[inputArray.length-1]*inputArray[inputArray.length-2];
}
}
return maxProdct;
}
Using python notations:
min( prod( v[ 0: ] ), prod( v[ 1: ] ), ..., prod( v[ -1 ] ) )
and max( prod( v[ 0: ] ), prod( v[ 1: ] ), ..., prod( v[ -1 ] ) )
in O(n)maxpro(v) = max( maxpro(v[:-1]) * max( prod( v[ 0: ] ), prod( v[ 1: ] ), ..., prod( v[ -1 ] ) )
. This is O(n) tooHere 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 )