HackerRank - Mini-Max Sum
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
Example
arr = [1, 3, 5, 7, 9]
The minimum sum is 1+3+5+7=16 and the maximum sum is 3+5+7+9=24 . The function prints
My code
修正前
一開始的想法,沒考慮到array中有可能有負數的作法 :
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
| public static void miniMaxSum(List<Integer> arr) {
// Write your code here
List<Integer> list = new ArrayList<>();
int sum = 0;
int min = 0;
for (int value : arr) {
sum += value;
}
min = sum;
int max = 0;
for (int value : arr) {
int sumWithoutValue = sum - value;
if( sumWithoutValue > max) {
max = sumWithoutValue;
}
if( sumWithoutValue < min) {
min = sumWithoutValue;
}
}
System.out.println(min + " " + max);
}
|
修正後
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
| import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'miniMaxSum' function below.
*
* The function accepts INTEGER_ARRAY arr as parameter.
*/
public static void miniMaxSum(List<Integer> arr) {
// Write your code here
long totalSum = 0;
long minSum = Long.MAX_VALUE;
long maxSum = Long.MIN_VALUE;
for (int value : arr) {
totalSum += value;
}
for (int value : arr) {
long sumWithoutValue = totalSum - value;
minSum = Math.min(minSum, sumWithoutValue);
maxSum = Math.max(maxSum, sumWithoutValue);
}
System.out.println(minSum + " " + maxSum);
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
List<Integer> arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Integer::parseInt)
.collect(toList());
Result.miniMaxSum(arr);
bufferedReader.close();
}
}
|