23년 8월 3일 [알고리즘 - sorting & thinking]

sua·2023년 8월 3일
0

알고리즘 가보자고

목록 보기
70/101

인프런 카드 가져가기

문제

나의 풀이

import java.util.Arrays;

public class TakeCard {
    public static int solution(int[] nums, int k) {
        int answer = 0;
        int n = nums.length;
        Integer[] tmp = Arrays.stream(nums).boxed().toArray(Integer[]::new);
        Arrays.sort(tmp, (a, b) -> b - a); // 카드들을 내림차순으로 정렬
        Integer[] diff = new Integer[n / 2]; // 라운드별 점수 차이 저장하는 배열
        for(int i = 0; i < n / 2; i++) {
            answer += tmp[i * 2 + 1]; // 매라운드에서 현수가 받을 수 있는 점수들 더하기
            diff[i] = tmp[i * 2] - tmp[i * 2 + 1]; // 매 라운드 점수 차이 계산
        }
        Arrays.sort(diff, (a, b) -> b - a); // 점수 차를 기준으로 내림차순 정렬
        for(int i = 0; i < k; i++) { // k번
            answer += diff[i]; // 점수 차이 더하기
        }
        return answer;
    }
    public static void main(String[] args) {
        System.out.println(TakeCard.solution(new int[]{7, 8, 5, 12, 3, 1, 3, 1, 1, 12}, 2));
        System.out.println(TakeCard.solution(new int[]{8, 2, 12, 12, 12, 12, 2, 2}, 2));
    }
}

기본형인 int 배열로 하면 내림차순 정렬을 할 수 없기 때문에 Integer형 배열을 사용하였다.

결과


인프런 심사위원

문제

나의 풀이

import java.util.Arrays;

public class Judges {
    public static int getAvg(int[] score, int s, int e) { // 평균 구하기
        int sum = 0;
        for(int i = s; i <= e; i++) {
            sum += score[i];
        }
        return (int) Math.floor((sum / (e - s + 1)));
    }
    public static int solution(int[] score, int k) {
        int n = score.length;
        Arrays.sort(score); // 점수 오름차순 정렬
        for(int i = 0; i <= n - k; i++) {
            if(score[i + k - 1] - score[i] <= 10) { // 구간에서 최고점수 최저점수 차가 10점 이하일 때
                return getAvg(score, i, i + k - 1); // 구간의 평균 점수 구하기
            }
        }
        return 0;
    }
    public static void main(String[] args) {
        System.out.println(Judges.solution(new int[]{99, 97, 80, 91, 85, 95, 92}, 3));
        System.out.println(Judges.solution(new int[]{92, 90, 77, 91, 70, 83, 89, 76, 95, 92}, 4));
    }
}

점수를 오름차순 정렬하면 재귀를 이용하지 않아도 쉽게 풀 수 있는 문제다.

결과

profile
가보자고

1개의 댓글

comment-user-thumbnail
2023년 8월 3일

정보에 감사드립니다.

답글 달기