|
| 1 | +package com.hackerrank.interviewpreparation.greedyalgorithmns; |
| 2 | + |
| 3 | +import java.io.BufferedWriter; |
| 4 | +import java.io.FileWriter; |
| 5 | +import java.io.IOException; |
| 6 | +import java.util.ArrayList; |
| 7 | +import java.util.Collections; |
| 8 | +import java.util.List; |
| 9 | +import java.util.Scanner; |
| 10 | + |
| 11 | +/** |
| 12 | + * @author rpatra16 |
| 13 | + * @since 04/11/2018 |
| 14 | + */ |
| 15 | +public class LuckBalance { |
| 16 | + |
| 17 | + /** |
| 18 | + * For the full question, please see: https://www.hackerrank.com/challenges/luck-balance/ |
| 19 | + * |
| 20 | + * @param k |
| 21 | + * @param contests |
| 22 | + * @return |
| 23 | + */ |
| 24 | + private static int luckBalance(int k, int[][] contests) { |
| 25 | + int lucks = 0; |
| 26 | + List<Integer> lucksForImportantContests = new ArrayList<>(); |
| 27 | + for (int i = 0; i < contests.length; i++) { |
| 28 | + if (contests[i][1] == 1) { |
| 29 | + lucksForImportantContests.add(contests[i][0]); |
| 30 | + } else { |
| 31 | + lucks += contests[i][0]; |
| 32 | + } |
| 33 | + } |
| 34 | + lucksForImportantContests.sort(Collections.reverseOrder()); |
| 35 | + for (int i = 0; i < lucksForImportantContests.size(); i++) { |
| 36 | + if (i < k) { // can lose at most k of the important contests |
| 37 | + lucks += lucksForImportantContests.get(i); |
| 38 | + } else { |
| 39 | + lucks -= lucksForImportantContests.get(i); |
| 40 | + } |
| 41 | + } |
| 42 | + return lucks; |
| 43 | + } |
| 44 | + |
| 45 | + private static final Scanner scanner = new Scanner(System.in); |
| 46 | + |
| 47 | + public static void main(String[] args) throws IOException { |
| 48 | + BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); |
| 49 | + |
| 50 | + String[] nk = scanner.nextLine().split(" "); |
| 51 | + |
| 52 | + int n = Integer.parseInt(nk[0]); |
| 53 | + |
| 54 | + int k = Integer.parseInt(nk[1]); |
| 55 | + |
| 56 | + int[][] contests = new int[n][2]; |
| 57 | + |
| 58 | + for (int i = 0; i < n; i++) { |
| 59 | + String[] contestsRowItems = scanner.nextLine().split(" "); |
| 60 | + scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); |
| 61 | + |
| 62 | + for (int j = 0; j < 2; j++) { |
| 63 | + int contestsItem = Integer.parseInt(contestsRowItems[j]); |
| 64 | + contests[i][j] = contestsItem; |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + int result = luckBalance(k, contests); |
| 69 | + |
| 70 | + bufferedWriter.write(String.valueOf(result)); |
| 71 | + bufferedWriter.newLine(); |
| 72 | + |
| 73 | + bufferedWriter.close(); |
| 74 | + |
| 75 | + scanner.close(); |
| 76 | + } |
| 77 | +} |
0 commit comments