222k views
5 votes
Given an array of intergers, find the greatest product of 3 integers within that array and return that product

1 Answer

4 votes

Answer & Explanation:

//written in java

import java.util.Arrays;

class Main {

//this function find the greatest product of 3

//integers within any array and return that product

private static int greatestProduct(int[] arr, int length) {

// if the size of array is less that 3

//the method return a value of 0

if (length < 3) {

return 0;

}

// the code below sort the array in ascending order

//multiply the last three, which is the product of the 3

//greatest value in the array

Arrays.sort(arr);

return arr[length - 1] * arr[length - 2] * arr[length - 3];

}

// the main method

public static void main(String[] args) {

int[] arr = {5, 3, 4, 2, 8, 10, 1};

int n = arr.length;

int product = greatestProduct(arr, n);

//if the size of array is less than 3

//greatestProduct(arr, n) return zero

//and the program print out

//"Size of array is less than three so product of 3 integers within that array does not exist"

//else it print the product of the three largest integer in the array

if (product == 0)

System.out.println("Size of array is less than three\\so product of 3 integers within that array does not exist");

else

System.out.println("Maximum product is " + product);

}

}

User Adrodoc
by
5.4k points