코딩테스트/구름톤 챌린지
[Java] 구름톤 챌린지 1주차 : 완벽한 햄버거 만들기
이덩우
2023. 8. 17. 12:20
- 문제설명
- 해결과정
주어진 배열에서 가장 큰 값과 그 인덱스를 찾고, 해당 인덱스를 기준으로 좌 우로 각각 오름차순, 내림차순 정렬이 되어있는지 확인하는 문제이다.
문제풀이는 아래와 같은 순서로 진행했다.
- 입력으로 주어진 숫자들을 int형 배열로 변환한다.
- 가장 큰 값의 인덱스를 찾는다.
- 해당 인덱스를 기준으로 배열을 2개로 쪼갠다.
- 좌측에 위치한 배열이 오름차순으로 정렬되어 있는지 확인한다.
- 우측에 위치한 배열이 내림차순으로 정렬되어 있는지 확인한다.
- 4,5번 둘다 만족하면 최초 만든 전체배열의 모든 요소를 더해 답으로 출력한다.
- 4,5번 둘 중 하나라도 만족하지 못한다면 0을 출력한다.
4,5번에서 원하는 정렬순서로 정렬되어있는지 판단하기 위해 똑같은 배열을 하나 복사해서 만들고, 복사된 배열을 오름차순, 내림차순으로 각각 정렬해 원본 배열과 내부 값이 동일한지 비교하는 방식을 사용했다.
- 솔루션
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int N = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int[] taste = new int[N];
int maxIndex;
for(int i = 0; i < N; i++) {
taste[i] = Integer.parseInt(st.nextToken());
}
maxIndex = findMaxIndex(taste);
int[] leftSide = Arrays.copyOfRange(taste, 0, maxIndex + 1);
int[] rightSide = Arrays.copyOfRange(taste, maxIndex, N);
int[] sortLeftSide = Arrays.copyOf(leftSide, leftSide.length);
Arrays.sort(sortLeftSide);
int[] sortRightSide = Arrays.copyOf(rightSide, rightSide.length);
Arrays.sort(sortRightSide);
int length = sortRightSide.length;
for(int i = 0; i < length / 2; i++) {
int temp = sortRightSide[i];
sortRightSide[i] = sortRightSide[length - i - 1];
sortRightSide[length - i - 1] = temp;
}
if(Arrays.equals(leftSide, sortLeftSide) && Arrays.equals(rightSide, sortRightSide)) {
bw.write(Integer.toString(sumArray(taste)));
bw.flush();
bw.close();
} else {
bw.write("0");
bw.flush();
bw.close();
}
}
private static int findMaxIndex(int[] taste) {
int maxIndex = 0;
int maxValue = 0;
for(int i = 0; i < taste.length; i++) {
if(taste[i] > maxValue) {
maxValue = taste[i];
maxIndex = i;
}
}
return maxIndex;
}
private static int sumArray(int[] taste) {
int sum = 0;
for(int a : taste) {
sum += a;
}
return sum;
}
}