less than 1 minute read

screencapture-codetree-ai-missions-5-problems-elemental-mean-value-for-a-particular-interval-description-2024-06-08-17_38_44


나의 풀이 코드

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // 입력
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        double[] arr = new double[n];
        for(int i = 0; i < n; i++) {
            arr[i] = sc.nextDouble();
        }

        // 구간 정해서 구간에 있는 원소들을 모두 더해서 평균 구하고 
        // 그 구간안에 동일한 원소가 있으면 cnt++
        int cnt = 0;
        for(int i = 0; i < n; i++) {
            //System.out.println("-----------");
            for(int j = i; j < n; j++) {
                double sumEle = 0;
                double cntEle = 0;
                for(int k = i; k <= j; k++) {
                    sumEle += arr[k];
                    cntEle++;
                }
                double avg = sumEle / cntEle;
                //System.out.println(avg + " = " + sumEle + "/" + cntEle);
                for(int k = i; k <= j; k++) {
                    if(avg == arr[k]) {
                        //System.out.println("    -->" + avg + " == " + arr[k]);
                        cnt++;
                        break;
                    }
                }
            }
        }
        System.out.println(cnt);
    }
}

완전탐색으로 푼 문제이다. 이때 주의할 점은 임의의 구간 안에서 해당하는 원소가 있는지 판별해야지 전체 구간에서 해당하는 원소가 있는지 판별하면 안된다.

Leave a comment