The max product of consecutive elements in an array

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

    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; iinputArray[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

提交回复
热议问题