如何在 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 中查找数组中两个乘积最大元素的不同方法。
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP