-
Notifications
You must be signed in to change notification settings - Fork 17
/
MaxSum.java
38 lines (33 loc) · 1.07 KB
/
MaxSum.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package by.andd3dfx.numeric;
import java.util.List;
/**
* <pre>
* Implement the findMaxSum() method that returns the largest sum of any two elements
* in the given list of positive numbers.
*
* For example, the largest sum of the list {5, 9, 7, 11} is the sum of the elements 9 and 11, which is 20.
* </pre>
*
* @see <a href="https://youtu.be/r6nFOKq_rdc">Video solution</a>
*/
public class MaxSum {
public static int find(List<Integer> list) {
if (list == null || list.size() < 2) {
throw new IllegalArgumentException("List size should be 2 at least!");
}
var m1 = Math.max(list.get(0), list.get(1));
var m2 = Math.min(list.get(0), list.get(1));
for (int i = 2; i < list.size(); i++) {
var item = list.get(i);
if (item > m1 || item > m2) {
if (item > m1) {
m2 = m1;
m1 = item;
} else {
m2 = item;
}
}
}
return m1 + m2;
}
}