길이 n인 서로다른 수로 이루어진 순열에서 현재 위치의 숫자와 앞의 숫자와 뒤의 숫자를 비교해서 현재 위치가 최대값도, 최소값도 아닌 수를 평범한 수라고 한다. 이 평범한 수의 갯수를 구하는 문제이다.
3 ≤ N ≤ 20 이므로 앞 뒤를 비교할 수 있는 1부터 n-2까지 순회하면서 현재 숫자가 평범한 숫자인지 직접 비교하여 갯수를 센다.
int count = 0;
for(int i=1; i<n-1; i++) {
int current = board[i];
int max = Math.max(board[i-1], Math.max(board[i], board[i+1]));
int min = Math.min(board[i-1], Math.min(board[i], board[i+1]));
if(current != max && current != min) count++;
}
결과 코드는 다음과 같다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();
for (int tc = 1; tc <= T; tc++) {
sb.append('#').append(tc).append(' ');
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int[] board = new int[n];
for(int i=0; i<n; i++) board[i] = Integer.parseInt(st.nextToken());
int count = 0;
for(int i=1; i<n-1; i++) {
int current = board[i];
int max = Math.max(board[i-1], Math.max(board[i], board[i+1]));
int min = Math.min(board[i-1], Math.min(board[i], board[i+1]));
if(current != max && current != min) count++;
}
sb.append(count).append('\n');
}
br.close();
System.out.print(sb);
}
}'알고리즘(백준 등) 공부' 카테고리의 다른 글
| SWEA 11592. 크루즈 컨트롤 (0) | 2026.05.30 |
|---|---|
| SWEA 11688. Calkin-Wilf tree 1 (0) | 2026.05.29 |
| SWEA 3819. 최대 부분 배열 (0) | 2026.05.28 |
| SWEA 12004. 구구단 1 (0) | 2026.05.27 |
| SWEA 12051. 프리셀 통계 (0) | 2026.05.26 |