Hackerrank – Problem Statement
A description of the problem can be found on Hackerrank.
Solution
I started with sorting the toys prices ascending. I looked at the prices from the beginning and sum the prices. If I exceeded the required given sum, I outputed the amount of toys.
I created solution in:
All solutions are also available on my GitHub profile.
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import scala.io.Source object Solution extends App { val lines = Source.stdin.getLines().toList val (n, k) = lines.head.split(" ").map(_.toInt).toList match { case a :: b :: Nil => (a, b) } val prices = lines.tail.head.split(" ").map(_.toInt).toList.sorted var sum = 0 val toys = prices.takeWhile(p => { sum += p p <= sum }) println(toys.length) } |
Java
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 |
import java.util.*; public class Solution { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int n = stdin.nextInt(); int k = stdin.nextInt(); int[] prices = new int[n]; for(int i = 0; i < n; i++) { prices[i] = stdin.nextInt(); } Arrays.sort(prices); int sum = 0; int toys = 0; for(int i = 0; i < n; i++) { int p = prices[i]; sum += p; if(sum > k) { break; } toys++; } System.out.println(toys); stdin.close(); } } |
Javascript
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 |
'use strict'; const processData = input => { const lines = input.split('\n'); const [n, k] = lines[0].split(' ').map(i => parseInt(i)); const prices = lines[1].split(' ').map(i => parseInt(i)).sort((a, b) => a-b); let sum = 0; let toys = 0; for(let i = 0; i < n; i++) { const p = prices[i]; sum += p; if(sum > k) { break; } toys++; } console.log(toys); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); let _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |