프로그래밍/Algorithm

[프로그래머스] 숫자 카드 나누기

일단개그하다 2022. 11. 11. 10:01

문제

https://school.programmers.co.kr/learn/courses/30/lessons/135807

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

접근 방법 및 풀이

문제 설명에는 명시되어 있지 않지만 각 배열은 오름차순으로 정렬 되어 있다고 추측
0번째 수가 가장 작은 숫자
2부터 배열의 0번째 숫자까지 해당 배열을 모두 나눌 수 있는 숫자를 찾기

A 배열을 모두 나눌 수 있는 숫자 중 B 배열을 모두 나눌 수 없는 숫자와 B 배열을 모두 나눌 수 있는 숫자 중 A 배열을 모두 나눌 수 없는 숫자 중 가장 큰 숫자를 반환

import java.util.ArrayList;
import java.util.List;

public class Q30_135807 {
    public int solution(int[] arrayA, int[] arrayB) {
        List<Integer> divisorsA = this.getDivisors(arrayA); // arrayA를 모두 나눌 수 있는 숫자
        List<Integer> divisorsB = this.getDivisors(arrayB); // arrayB를 모두 나눌 수 있는 숫자

        int targetA = this.getMaxNonDivisor(arrayB, divisorsA);
        int targetB = this.getMaxNonDivisor(arrayA, divisorsB);

        return Math.max(targetA, targetB);
    }

    public int getMaxNonDivisor(int[] arrays, List<Integer> divisors) {
        int target = 0;
        for (int divisor : divisors) {
            boolean isNoDivide = true;
            for (int number : arrays) {
                if (number % divisor == 0) {
                    isNoDivide = false;
                    break;
                }
            }
            if (isNoDivide) {
                target = Math.max(target, divisor);
            }
        }
        return target;
    }

    public List<Integer> getDivisors(int[] arrays) {
        List<Integer> list = new ArrayList<>();
        int length = arrays.length;
        int min = arrays[0];
        for (int i = 2; i <= min; i++) {
            boolean isDivide = true;
            for (int j = 0; j < length; j++) {
                if (arrays[j] % i != 0) {
                    isDivide = false;
                    break;
                }
            }
            if (isDivide) {
                list.add(i);
            }
        }
        return list;
    }
}