Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Problem
- Three brothers walk into a bar. All the beverages are placed in one line at the long bar table. The size of each glass is represented in an array of integers, glasses.
- The brothers will drink a round if they can find 3 consecutive glasses of the same size. The barman removes the empty glasses from the table immediately after each round.
- Find the maximum number of rounds the three brothers can drink.
- Example
- For glasses = [1, 1, 2, 3, 3, 3, 2, 2, 1, 1], the output should be brothersInTheBar(glasses) = 3.
- The brothers can start with a round of size 3, then after the glasses are cleared, a round of size 2 can be formed, followed by a round of size 1. One glass will be left at the table.
- [input] array.integer glasses
- The sizes of glasses in the row.
- Guaranteed constraints:
- 1 ≤ glasses.length ≤ 105,
- 1 ≤ glasses[i] ≤ 106.
- [output] integer
- The maximum number of rounds the brothers can drink.
- Grading
- The example case passes - 5%
- Happy path covered - 5%
- Corner cases covered - 20%
- Error handling - 10%
- Optimization - 40%
- Code formatting - 10%
- Naming conventions - 10%
- ************************************************
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.Arrays;
- public class Main {
- private final static int consecutiveGlassesNeeded = 3;
- public static void main(String[] args) throws IOException {
- BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
- System.out.println("Please insert numbers with single space between them:");
- int[] glasses = Arrays.stream(reader.readLine().split("\\s+")).mapToInt(Integer::parseInt).toArray();
- int rounds = 0;
- int countGlassesOfSameSize = 1;
- while (glasses.length >= 3){
- for (int glassPos = 0; glassPos < glasses.length - 1; glassPos++) {
- if (glasses[glassPos] == glasses[glassPos + 1]){
- countGlassesOfSameSize++;
- if (countGlassesOfSameSize == consecutiveGlassesNeeded){
- rounds++;
- //removing process
- glasses = removeTheElements(glasses, glassPos - 1);
- //starting over from the beginning of the array
- break;
- }
- }else {
- countGlassesOfSameSize = 1;
- }
- }
- //end the program when there aren't any more consecutive glasses
- if (countGlassesOfSameSize < consecutiveGlassesNeeded){
- break;
- }
- //restart the counter
- countGlassesOfSameSize = 1;
- }
- System.out.println(String.format("Tonight the brothers can drink in %d rounds only", rounds));
- }
- private static int[] removeTheElements(int[] arr, int index){
- int[] anotherArray = new int[arr.length - consecutiveGlassesNeeded];
- for (int arrPos = 0, newArrPos = 0; arrPos < arr.length; arrPos++) {
- if (arrPos == index){
- arrPos += 2;
- continue;
- }
- anotherArray[newArrPos++] = arr[arrPos];
- }
- return anotherArray;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement