HackerRank problem solving solution in Java | HackerRank Solutions in Java | AskTheCode
Problem:
You are in charge of the cake for a child's birthday. You have decided the cake will have one candle for each year of their total age. They will only be able to blow out the tallest of the candles. Count how many candles are tallest.
Example
candles = [4, 4, 1, 3]
The maximum height candles are 4 units high. There are 2 of them, so return 2.
Function Description
Complete the function birthdayCakeCandles.
birthdayCakeCandles has the following parameter(s):
int candles[n]: the candle heights
Returns
int: the number of candles that are tallest
Note: This solution provided here is a way to solve this problem, there can be other ways too.
Input:
The first line contains a single integer, n, the size of candles[].
The second line contains n space-separated integers, where each integer i describes the height of candles[i].
Output:
For each test case, output in a single line the answer to the problem.
Sample Input:
4
3 2 1 3
Sample Output:
2
EXPLANATION:
The problem is given states that you are given a list of candles of different heights. And, a condition is stated that, only the tallest candles can be blown out. Therefore, you are assigned to find the number of candles that can be blown out.
Here, you've to find the number of occurrence of the largest data present in the given ArrayList or Array.
Brute Force Approach:
Sort the given Array/ArrayList, and then, count the max. value from the last index of the Array/ArrayList. When you get any different value other than the largest data, then break out of the loop, and return the counted values.
Code:
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
class Result {
public static int birthdayCakeCandles(List<Integer> candles) {
Integer[] arr = new Integer[candles.size()];
arr = candles.toArray(arr);
Arrays.sort(arr);
int i = arr.length-1, x = arr[i], count = 0;
while(i >= 0){
if(arr[i] == x)
count++;
else
break;
i--;
}
return count;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int candlesCount = Integer.parseInt(bufferedReader.readLine().trim());
String[] candlesTemp = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");
List<Integer> candles = new ArrayList<>();
for (int i = 0; i < candlesCount; i++) {
int candlesItem = Integer.parseInt(candlesTemp[i]);
candles.add(candlesItem);
}
int result = Result.birthdayCakeCandles(candles);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
Comentarios