Hackerrank – Popis problému
Celý popis zadania sa nacháza – Hackerrank.
Riešenie
Urobím to, čo je napísané v zadaní. Hľadám také dvojice klávesnice a usb, ktoré sa najviac približujú požadovanej cene zľava.
Vytvoril som riešenie v týchto programovacích jazykoch:
Všetky riešenia sú dostupné aj na mojom GitHub profile.
Scala
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 |
import scala.io.Source object Solution extends App { val lines = Source.stdin.getLines().toList val (s, n, m) = lines.head.split(" ").map(_.toInt).toList match { case a :: b :: c :: Nil => (a, b, c) } val keyboards = lines(1).split(" ").map(_.toInt) val usbs = lines(2).split(" ").map(_.toInt) val allSmallerThanS = (for { i <- 0 until n j <- 0 until m } yield (i, j)).toList.filter { a => keyboards(a._1) + usbs(a._2) <= s } val sum = if(allSmallerThanS.isEmpty) { -1 } else { val indexes = allSmallerThanS.maxBy { a => keyboards(a._1) + usbs(a._2) } keyboards(indexes._1) + usbs(indexes._2) } println(sum) } |
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 29 30 31 |
import java.util.*; public class Solution { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int amount = stdin.nextInt(); int keyboardCount = stdin.nextInt(); int usbCount = stdin.nextInt(); int[] keyboards = new int[keyboardCount]; int[] usbs = new int[usbCount]; for(int i = 0; i < keyboardCount; i++) { keyboards[i] = stdin.nextInt(); } for(int i = 0; i < usbCount; i++) { usbs[i] = stdin.nextInt(); } int spentAmount = -1; for(int i = 0; i < keyboardCount; i++) { for(int j = 0; j < usbCount; j++) { int sum = keyboards[i] + usbs[j]; if(sum <= amount && sum > spentAmount) { spentAmount = sum; } } } System.out.println(spentAmount); 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 [amount, keyboardCount, usbCount] = lines[0].split(' ').map(i => parseInt(i)); const keyboards = lines[1].split(' ').map(i => parseInt(i)); const usbs = lines[2].split(' ').map(i => parseInt(i)); let spentAmount = -1; for(let i = 0; i < keyboardCount; i++) { for(let j = 0; j < usbCount; j++) { let sum = keyboards[i] + usbs[j]; if(sum <= amount && sum > spentAmount) { spentAmount = sum; } } } console.log(spentAmount); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); let _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |