|
| 1 | +package hackerRank_JavaProblemSolving; |
| 2 | + |
| 3 | +import java.io.BufferedWriter; |
| 4 | +import java.io.FileWriter; |
| 5 | +import java.io.IOException; |
| 6 | +import java.util.Arrays; |
| 7 | +import java.util.Scanner; |
| 8 | + |
| 9 | +public class Problem086_Mark_andToys__GreedyAlgorithm { |
| 10 | + |
| 11 | + // IDEAS: Stupid greedy algorithm |
| 12 | + static int maximumToys(int[] prices, int k) { |
| 13 | + Arrays.sort(prices); |
| 14 | + int sum = 0; |
| 15 | + int counter = 0; |
| 16 | + for (int p : prices) { |
| 17 | + sum += p; |
| 18 | + counter++; |
| 19 | + if ( sum > k ) { |
| 20 | + counter--; |
| 21 | + break; |
| 22 | + } |
| 23 | + } |
| 24 | + return counter; |
| 25 | + } // maximumToys |
| 26 | + |
| 27 | + private static final Scanner scanner = new Scanner(System.in); |
| 28 | + |
| 29 | + public static void main(String[] args) throws IOException { |
| 30 | + BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); |
| 31 | + |
| 32 | + String[] nk = scanner.nextLine().split(" "); |
| 33 | + |
| 34 | + int n = Integer.parseInt(nk[0]); |
| 35 | + |
| 36 | + int k = Integer.parseInt(nk[1]); |
| 37 | + |
| 38 | + int[] prices = new int[n]; |
| 39 | + |
| 40 | + String[] pricesItems = scanner.nextLine().split(" "); |
| 41 | + scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); |
| 42 | + |
| 43 | + for (int i = 0; i < n; i++) { |
| 44 | + int pricesItem = Integer.parseInt(pricesItems[i]); |
| 45 | + prices[i] = pricesItem; |
| 46 | + } |
| 47 | + |
| 48 | + int result = maximumToys(prices,k); |
| 49 | + |
| 50 | + bufferedWriter.write(String.valueOf(result)); |
| 51 | + bufferedWriter.newLine(); |
| 52 | + |
| 53 | + bufferedWriter.close(); |
| 54 | + |
| 55 | + scanner.close(); |
| 56 | + } |
| 57 | +} |
| 58 | + |
0 commit comments