백준 17615 볼 모으기 JAVA -> 100점Algorithm2024. 5. 8. 18:42
Table of Contents
package com.test.backjoon;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class B_17165 {
// 백준 17615 볼 모으기 JAVA
private static int N;
private static String[] arr;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 왼쪽 오른쪽
// 파랑 빨강 => Math.min(빨간색 움직이는 횟수, 파랑색 움직이는 횟수)
// 빨강 파랑
N = Integer.parseInt(br.readLine());
arr = br.readLine().split("");
int result = 0;
int redCnt = 0;
int blueCnt = 0;
for (String color : arr) {
if (color.equals("R")) redCnt++;
if (color.equals("B")) blueCnt++;
}
if (redCnt == 0 || blueCnt == 0) {
System.out.println(result);
return;
}
// 파랑 빨강
int cntRedMove = getCountBallMove("R", true);
int cntBlueMove = getCountBallMove("B", false);
result = Math.min(cntRedMove, cntBlueMove);
// 빨강 파랑
cntRedMove = getCountBallMove("R", false);
result = Math.min(result, cntRedMove);
cntBlueMove = getCountBallMove("B", true);
result = Math.min(result, cntBlueMove);
System.out.println(result);
}
private static int getCountBallMove(String color, boolean toRight) {
int count = 0;
if (toRight) {
int idx = N-1;
for (int i = N-2 ; i >= 0 ; i--) {
// 가장 오른쪽의 덩어리에 있는 맨 앞 요소 idx / 다른 색이 나오면 break
if (arr[N-1].equals(arr[i])) idx = i;
else break;
}
for (int i = 0 ; i < idx ; i++) {
if (color.equals(arr[i])) count++;
}
}
if (!toRight) {
int idx = 0;
for (int i = 1 ; i < N ; i++) {
// 가장 왼쪽의 덩어리에 있는 맨 뒤 요소 idx / 다른 색이 나오면 break
if (arr[0].equals(arr[i])) idx = i;
else break;
}
for (int i = N-1 ; i > idx ; i--) {
if (color.equals(arr[i])) count++;
}
}
return count;
}
}
'Algorithm' 카테고리의 다른 글
[완전탐색] 백준 1189 컴백홈 JAVA (0) | 2024.04.30 |
---|---|
[구현] 백준 1205 등수구하기 JAVA (0) | 2024.04.27 |
[완전탐색] 백준 2529 부등호 JAVA (0) | 2024.04.20 |
[그리디] 백준 11047 동전0 JAVA (1) | 2024.04.20 |
[구현] 백준 8979 올림픽 JAVA (1) | 2024.04.19 |