Hackerrank – Flowers
Problem Statement A description of the problem can be found on Hackerrank. Solution Sort all prices descending. The formula for calculating the flower i in prices: $$total = \sum_{i=0}^{n-1}((i / k + 1) * price_{i})$$ I created solution in: Java JavaScript Ruby Scala 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 21 22 23 24 25 26 27 28 29 |
import java.util.*; public class Flowers { private static class Descending implements Comparator<Integer> { @Override public int compare(Integer i, Integer j) { return j - i; } } public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int n = stdin.nextInt(); int k = stdin.nextInt(); Integer[] prices = new Integer[n]; for(int i = 0; i < n; i++) { prices[i] = stdin.nextInt(); } Arrays.sort(prices, new Descending()); int sum = 0; for(int i = 0; i < n; i++) { int factor = i / k; sum += prices[i] * (factor + 1); } System.out.println(sum); 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 |
'use strict'; const processData = input => { let lines = input.split('\n'); let definition = lines[0].split(' ').map(i => parseInt(i)); let n = definition[0]; let k = definition[1]; let prices = lines[1].split(" ").map(i => parseInt(i)); let descendingPrices = prices.sort((i, j) => j - i); let totalPrice = 0; for(let i = 0; i < n; i++) { let factor = parseInt(i / k); totalPrice += (factor + 1) * descendingPrices[i]; } console.log(totalPrice); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); var _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |