[SWEA / Java] 1206. [S/W 문제해결 기본] 1일차 - View

이하얀·2024년 5월 12일
0

🧢 SWEA

목록 보기
4/10
post-thumbnail

💡 Info



💭 문제 이해

  • 빌딩들에 대한 정보가 주어지면 -> 조망권 확보 세대 수 반환!

📥입력 조건

  • 총 10개의 테스트케이스가 주어진다.
  • 각 테스트케이스의 첫 번째 줄에는 건물의 개수 N이 주어진다. (4 ≤ N ≤ 1000)
  • 그 다음 줄에는 N개의 건물의 높이가 주어진다. (0 ≤ 각 건물의 높이 ≤ 255)
  • 맨 왼쪽 두 칸과 맨 오른쪽 두 칸에 있는 건물은 항상 높이가 0이다. (예시에서 빨간색 땅 부분)
10
0 0 254 185 76 227 84 175 0 0
10
0 0 251 199 176 27 184 75 0 0
11
0 0 118 90 243 178 99 100 200 0 0
...

📤출력 조건

  • #부호와 함께 테스트케이스의 번호를 출력하고, 공백 문자 후 조망권이 확보된 세대의 수를 출력한다.
#1 111
#2 60
#3 165
...


💭 생각한 알고리즘

실제 풀이 시간 : 45분

  • 10개의 테스트 케이스를 입력받기
  • count를 통해 조망권 확보 세대 수 세기
    • i = 0 부터 i < n 까지의 i 범위에서 Math.max를 이용해 array[i-2]Math.max(array[i+1], array[i+2])를 비교해 큰 값을 반환하기
    • 즉, 주변 집을 모두 분석해 양쪽 거리 2 이상의 거리를 확보했는지 여부를 파악하는 것
import java.util.*;
 
class Solution
{
    static int n;
    static int[] array;
 
    public static void main(String args[]) throws Exception {
        Scanner sc = new Scanner(System.in);
         
        int T=10;
 
        for (int test_case = 1; test_case <= T; test_case++) {
            n = sc.nextInt();
            array = new int[n];
            for (int i = 0; i < n; i++) {
                array[i] = sc.nextInt();
            }
 
            int count = 0;
            for (int i = 0; i < n; i++) {
                int max = Math.max(array[i-2],
                        Math.max(array[i-1],
                                Math.max(array[i+1], array[i+2])));
                 
                if (array[i] > max)
                    count += array[i] - max;
            }
            System.out.println("#" + test_case + " " + count);
        }
    }
}


❌ 오답체크

  • count의 n 범위가 잘못되어 발생한 문제
  • n을 0부터가 아닌 2부터 n-2까지로 변경해야 함!!
     int count = 0;
     for (int i = 2; i < n-2; i++) {
     ...


💭 최종 풀이

  • 10개의 테스트 케이스를 입력받기
  • count를 통해 조망권 확보 세대 수 세기
    • i = 2 부터 i < n-2 까지의 i 범위에서 Math.max를 이용해 array[i-2]Math.max(array[i+1], array[i+2])를 비교해 큰 값을 반환하기
    • 즉, 주변 집을 모두 분석해 양쪽 거리 2 이상의 거리를 확보했는지 여부를 파악하는 것
import java.util.*;
 
class Solution
{
    static int n;
    static int[] array;
 
    public static void main(String args[]) throws Exception {
        Scanner sc = new Scanner(System.in);
         
        int T=10;
 
        for (int test_case = 1; test_case <= T; test_case++) {
            n = sc.nextInt();
            array = new int[n];
            for (int i = 0; i < n; i++) {
                array[i] = sc.nextInt();
            }
 
            int count = 0;
            for (int i = 2; i < n-2; i++) {
                int max = Math.max(array[i-2],
                        Math.max(array[i-1],
                                Math.max(array[i+1], array[i+2])));
                 
                if (array[i] > max)
                    count += array[i] - max;
            }
            System.out.println("#" + test_case + " " + count);
        }
    }
}

profile
언젠가 내 코드로 세상에 기여할 수 있도록, BE 개발 기록 노트☘️

0개의 댓글