[알고리즘] Flatten

2024. 1. 30. 10:35알고리즘 풀이/Java

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV139KOaABgCFAYh

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

package swea.flatten;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Solution {
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		for (int testCase = 0; testCase < 10; testCase++) {
			int n = Integer.parseInt(br.readLine());
			st = new StringTokenizer(br.readLine(), " ");
			int[] boxHeights = new int[100];
			for (int i = 0; i < 100; i++) {
				int height = Integer.parseInt(st.nextToken());
				boxHeights[i] = height;
			}
			System.out.println("#" + (testCase + 1) + " " + findMinimumGap(boxHeights, n));
		}
		
	}
	
	private static int findMaxHeightIndex(int[] boxHeights) {
		int maxHeight = Integer.MIN_VALUE;
		int maxHeightIndex = -1;
		for (int i = 0; i < boxHeights.length; i++) {
			if (maxHeight < boxHeights[i]) {
				maxHeightIndex = i;
				maxHeight = boxHeights[i];
			}
		}
		return maxHeightIndex;
		
	}
	private static int findMinHeightIndex(int[] boxHeights) {
		int minHeight = Integer.MAX_VALUE;
		int minHeightIndex = -1;
		for (int i = 0; i < boxHeights.length; i++) {
			if (minHeight > boxHeights[i]) {
				minHeightIndex = i;
				minHeight = boxHeights[i];
			}
		}
		return minHeightIndex;
		
	}
	private static int findMinimumGap(int[] boxHeights, int n) {
		for (int i = 0; i < n; i++) {
			int maxHeightIndex = findMaxHeightIndex(boxHeights);
			int minHeightIndex = findMinHeightIndex(boxHeights);
			boxHeights[maxHeightIndex]--;
			boxHeights[minHeightIndex]++;
		}
		int maxHeightIndex = findMaxHeightIndex(boxHeights);
		int minHeightIndex = findMinHeightIndex(boxHeights);
		
		return boxHeights[maxHeightIndex] - boxHeights[minHeightIndex];
	}
}

 

나의 풀이

- 쉽게쉽게 생각했다.

- 각 덤프마다 최대 높이 인덱스와 최저 높이 인덱스를 구해서 각각의 높이를 하나 빼고 더해주고를 반복했다.

- 그리고 마지막에 최대 높이와 최저 높이를 다시 구해서 차이를 반환해주었다.
- 조건이 까다롭지 않다면 복잡하게 하기 보다는 간단하게 먼저 완전탐색부터 시도해보자!!!!!