HackerRank : University CodeSprint – Mini-Max Sum

By | November 12, 2016

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.

Input Format

A single line of five space-separated integers.

Constraints

  • Each integer is in the inclusive range [1 – 10^9] .

Output Format

Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers.

Sample Input

1 2 3 4 5

Sample Output

10 14

Solution

I have stored the inputs in a ArrayList.
Sorted it.
And, added first four inputs to get min as required and added
last 4 to get max as required.

catch:  take care of memory overflow by using bigger data type.

Code:

package universityCodeSprint;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class MiniMaxSum {
	
	public static void main(String[] args) {
		
		Scanner scan=new Scanner(System.in);
		
		List list= new ArrayList();
		long minsum=0, maxsum=0;
		
		for(int i=0;i<5;i++)
			list.add(scan.nextLong());
		
		Collections.sort(list);
		
		for(int i=0;i<4;i++)
			minsum=minsum+ list.get(i);
		
		for(int i=1;i<5;i++)
			maxsum=maxsum+ list.get(i);
		
		System.out.println(minsum+" "+maxsum);

	}
}