Reputation: 45
There is a very famous and simple problem on hacker-rank that goes as follows:
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.
Now, i solved this problem as follows:
long max = Collections.max(intList);
long min = Collections.min(intList);
long sum = intList.stream().mapToInt(Integer::intValue).sum();
System.out.println((sum-max)+" "+(sum-min));
It works, but is falling short of 3 test cases. Any suggestions, or improvements that can be done? I am trying to improve my programming skills and this is something that i dont want to let go till i completely understand.
Thanks!
EDIT
Here is the improved code and the answer to anyone who is looking :
long max = Collections.max(arr);
long min = Collections.min(arr);
long sum = arr.stream().mapToLong(Integer::longValue).sum();
System.out.println((sum-max)+" "+(sum-min));
Upvotes: 1
Views: 642
Reputation: 46953
The only problem I see is that you are expected to calculate long
result, but are calculating intermediary values (e.g. total sum) in int
. This can result in type overflow.
Basically substitute mapToInt
with mapToLong
and use rather longValue
.
PS: Otherwise I like your solution in the sense it is concise and utilizes APIs well. If you are after pixel perfect performance you might want to spare unnecessary cycles over the list, but this is really extreme optimization (as your solution is also linear in complexity) and I doubt it will ever make a difference.
Upvotes: 2