Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Min Max Problem:Short Solution falling short of 3 test cases out of 15

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading