We can easily find two number in an array whose product is maximum using the below approach:
Sort the input integer array in descending order
multiply first and second element of the array, the product will be maximum.Find product of max two elements of an integer array
import java.util.Arrays; import java.util.Comparator; public class ArrayUtils { long productMinMax(Integer[] array) { Arrays.sort(array, Comparator.reverseOrder()); int maxNumber = array[0]; int secondMaxNumber = array[1]; System.out.println("maxNumber = " + maxNumber); System.out.println("secondMaxNumber = " + secondMaxNumber); return secondMaxNumber * maxNumber; } public static void main(String[] args) { long product = new ArrayUtils().productMinMax(new Integer[]{10, 11, 13, 9, 2, 4}); System.out.println("Product of min and max element = " + product); } }
Program outputmaxNumber = 13 secondMaxNumber = 11 Product of min and max element = 143
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.