在Java中查找两个数组元素的最大和
Two elements giving the maximum sum in an array means, we have to find two largest array elements which will eventually give the maximum sum possible.
In this article we will see how we can find the maximum sum of two elements in Java.
To show you some instances
Instance-1
Suppose we have the below array
[10, 2, 3, -5, 99, 12, 0, -1]
In this array the largest element is 99 and second largest is 12.
Max sum = 99 + 12
因此,这个数组中两个元素的最大和为111。
Instance-2
Suppose we have the below array
[556, 10, 259, 874, 123, 453, -96, -54, -2369]
在这个数组中,最大的元素是874,第二大的元素是556。
Max sum = 874+556
因此,该数组中两个元素的最大和为1430。
Instance-3
Suppose we have the below array
[55, 10, 29, 74, 12, 45, 6, 5, 269]
在这个数组中,最大的元素是269,第二大的元素是74。
Max sum= 269+74
因此,该数组中两个元素的最大和为343。
Algorithm
算法-1
步骤 1 − 使用 for 循环在数组中找到最大和第二大的元素。
步骤 2 - 找到它们的和。
Step 3 − Print the sum.
Algorithm-2
Step 1 − Sort the array elements.
Step 2 −Take the last and second last element of the array.
Step 3 − Find their sum.
Step 4 − Print the sum.
Syntax
To sort the array we need to use the sort( ) method of the Arrays class of java.util package.
Following is the syntax to sort any array in ascending order using the method
Arrays.sort(array_name);登录后复制