如何在 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 中查詢陣列中兩個乘積最大元素的不同方法。

更新於: 2023 年 3 月 6 日

1K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.