Java 找到两个数组元素的最大乘积
在数组中找到两个乘积最大的元素意味着我们必须找到两个最大的数组元素,这最终会给出可能的最大乘积。
在本文中,我们将看到如何在Java中找到两个元素的最大乘积。
为了给您展示一些实例
实例1
假设我们有以下数组
[10, 2, 3, -5, 99, 12, 0, -1]
在这个数组中,最大的元素是99,第二大的元素是12。
最大乘积= 99 * 12
因此,这个数组中两个元素的最大乘积是1188。
实例2
假设我们有以下数组
[6, 1, 2, 4, 3, 5, 9]
在这个数组中,最大的元素是9,第二大的元素是6。
最大乘积 = 9 * 6
因此,这个数组中两个元素的最大乘积是54。
实例3
假设我们有以下数组
[10, 17, 14, 12, 15, 6, 5, 19]
在这个数组中,最大的元素是19,第二大的元素是17。
最大乘积 = 19 * 17
因此,这个数组中两个元素的最大乘积是323。
步骤
步骤1
步骤1 - 使用for循环在数组中找到最大和第二大的元素。
步骤2 - 找到它们的乘积。
步骤3 - 打印乘积。
步骤2
步骤1 - 对数组元素进行排序。
步骤2 - 取数组的最后一个和倒数第二个元素。
步骤3 - 找到它们的乘积。
步骤4 - 打印乘积。
语法
为了对数组进行排序,我们需要使用java.util包中的Arrays类的sort()方法。
以下是使用该方法按升序对任何数组进行排序的语法-
Arrays.sort(array_name);
其中,’array_name’是你想要排序的数组。
多种方法
我们提供了不同的方法来解决问题。
- 使用for循环找到最大乘积。
-
使用Arrays.sort找到最大乘积。
让我们逐个看看程序及其输出。
方法1:使用for循环
在这个方法中,我们使用for循环来遍历数组元素,找出最大和第二大的元素。这两个元素将给出最大的乘积。
示例
public class Main {
public static void main(String[] args) {
// The array elements
int arr[] = { 10, 2, 3, -5, 99, 12, 0, -1 };
// Storing the first element in both variables
int first = arr[0], second = arr[0];
// For loop to iterate the elements from 1 to n
// to find the first largest element
for (int i = 0; i < arr.length; i++) {
// If array element is larger than current largest element, then swap
if (arr[i] > first)
first = arr[i];
}
// For loop to iterate the elements from 1 to n
// to find the second largest element
for (int i = 0; i < arr.length; i++) {
// If array element is larger than current largest element and not equals to
// largest element, then swap
if (arr[i] > second && arr[i] != first)
second = arr[i];
}
// Print the product
System.out.println("Largest product = " + (first * second));
System.out.println("The elements are " + first + " and " + second);
}
}
输出
Largest product = 1188
The elements are 99 and 12
方法2:使用Arrays.sort
在这个方法中,我们使用Arrays.sort()方法对数组进行排序。然后我们取最后一个和倒数第二个索引位置上的元素。由于数组已经排序,这两个元素将给出最大的乘积。
示例
import java.util.Arrays;
public class Main{
public static void main(String[] args) {
// The array elements
int arr[] = { 10, 2, 3, -5, 9, 12, 0, -1 };
// Sort the array using the sort method from array class
Arrays.sort(arr);
// Storing the last element as largest and second last element as second largest
int first = arr[arr.length - 1], second = arr[arr.length - 2];
// Print the maximum product
System.out.println("Maximum product = " + (first * second));
System.out.println("The elements are " + first + " and " + second);
}
}
输出
Maximum product = 120
The elements are 12 and 10
在本文中,我们探讨了在Java中寻找数组中乘积最大的两个元素的不同方法。