Hackerrank – Problem Statement
A description of the problem can be found on Hackerrank.
Solution
If you order the given array ascending
– the min sum are first n-1
elements
– the max sum are last n-1
elements
I created solution in:
All solutions are also available on my GitHub.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.*; public class MiniMaxSum { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); Object[] numbers = Arrays.stream(stdin.nextLine().split(" ")) .map(Long::parseLong).toArray(); Arrays.sort(numbers); long minSum = 0; long maxSum = 0; for(int i = 0; i < numbers.length - 1; i++) { minSum += (long) numbers[i]; maxSum += (long) numbers[i + 1]; } System.out.println(minSum + " " + maxSum); stdin.close(); } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
'use strict'; const processData = input => { const numbers = input.split(" ").map(i => parseInt(i)); numbers.sort((a, b) => a - b) let minSum = 0; let maxSum = 0; for(let i = 0; i < numbers.length - 1; i++) { minSum += numbers[i]; maxSum += numbers[i + 1]; } console.log(minSum + " " + maxSum); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); let _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |
Scala
1 2 3 4 5 6 7 8 9 |
object MinMaxSum { def main(args: Array[String]) { val ints = scala.io.Source.stdin.getLines.toList.head.split(" ").map(_.toLong) val minsum = ints.sorted.init.sum val maxsum = ints.sorted.tail.sum println(minsum + " " + maxsum) } } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 |
nums = gets.strip.split(" ").map(&:to_i) nums.sort! {|a, b| a <=> b} min_sum = 0 max_sum = 0 for i in (0...(nums.length - 1)) do min_sum += nums[i] max_sum += nums[i + 1] end puts "" + min_sum.to_s + " " + max_sum.to_s |