Advertisement
JeffGrigg

FindLargestProduct

Aug 22nd, 2017
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.04 KB | None | 0 0
  1. public class FindLargestProduct {
  2.  
  3.     public static int adjacentElementsProduct(final int[] inputArray) {
  4.         if (inputArray == null) {
  5.             throw new IllegalArgumentException("Input array must not be null.");
  6.         }
  7.         if (inputArray.length < 2) {
  8.             throw new IllegalArgumentException("Minimum array size is two elements.");
  9.         }
  10.  
  11.         int largestProduct = Integer.MIN_VALUE;
  12.         for (int index = 0; index < inputArray.length - 1; ++index) {   // (one less than the end, due to "index + 1" reference below]
  13.             final int thisProduct = inputArray[index] * inputArray[index + 1];
  14.             if (thisProduct >= largestProduct) {
  15.                 largestProduct = thisProduct;
  16.             }
  17.         }
  18.         return largestProduct;
  19.     }
  20.  
  21.     public static void main(final String[] args) {
  22.         final int[] inputArray = {3, 6, -2, -5, 7, 3};
  23.         final int largestProduct = FindLargestProduct.adjacentElementsProduct(inputArray);
  24.         System.out.println(largestProduct);
  25.     }
  26.  
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement