01-09 04:37
Recent Posts
Recent Comments
๊ด€๋ฆฌ ๋ฉ”๋‰ด

miinsun

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_34 K๋ฒˆ์งธ ํฐ ์ˆ˜ ๋ณธ๋ฌธ

Algorithm/Java

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_34 K๋ฒˆ์งธ ํฐ ์ˆ˜

miinsun 2022. 1. 5. 19:50

 

๐Ÿ’ฌ ๋ฌธ์ œ ์„ค๋ช…

ํ˜„์ˆ˜๋Š” 1๋ถ€ํ„ฐ 100์‚ฌ์ด์˜ ์ž์—ฐ์ˆ˜๊ฐ€ ์ ํžŒ N์žฅ์˜ ์นด๋“œ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.
๊ฐ™์€ ์ˆซ์ž์˜ ์นด๋“œ๊ฐ€ ์—ฌ๋Ÿฌ์žฅ ์žˆ์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

ํ˜„์ˆ˜๋Š” ์ด ์ค‘ 3์žฅ์„ ๋ฝ‘์•„ ๊ฐ ์นด๋“œ์— ์ ํžŒ ์ˆ˜๋ฅผ ํ•ฉํ•œ ๊ฐ’์„ ๊ธฐ๋กํ•˜๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค.
3์žฅ์„ ๋ฝ‘์„ ์ˆ˜ ์žˆ๋Š” ๋ชจ๋“  ๊ฒฝ์šฐ๋ฅผ ๊ธฐ๋กํ•ฉ๋‹ˆ๋‹ค.

๊ธฐ๋กํ•œ ๊ฐ’ ์ค‘ K๋ฒˆ์งธ๋กœ ํฐ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์„ธ์š”.

๋งŒ์•ฝ ํฐ ์ˆ˜๋ถ€ํ„ฐ ๋งŒ๋“ค์–ด์ง„ ์ˆ˜๊ฐ€ 25 25 23 23 22 20 19......์ด๊ณ 
K๊ฐ’์ด 3์ด๋ผ๋ฉด K๋ฒˆ์งธ ํฐ ๊ฐ’์€ 22์ž…๋‹ˆ๋‹ค.

 

 

๐Ÿ”จ ์ž…์ถœ๋ ฅ ์˜ˆ

์ž…๋ ฅ - ์ฒซ ์ค„์— ์ž์—ฐ์ˆ˜ N(3<=N<=100)๊ณผ K(1<=K<=50) ์ž…๋ ฅ๋˜๊ณ , ๊ทธ ๋‹ค์Œ ์ค„์— N๊ฐœ์˜ ์นด๋“œ๊ฐ’์ด ์ž…๋ ฅ๋œ๋‹ค.

10 3
13 15 34 23 45 65 33 11 26 42

์ถœ๋ ฅ - ์ฒซ ์ค„์— K๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค. K๋ฒˆ์งธ ์ˆ˜๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฉด -1๋ฅผ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

143

 

 

๐Ÿ’ป Solution.java

import java.util.*;

public class Main {

	public int solution(int[] arr, int k) {
		int answer = -1;
		TreeSet<Integer> Tset = new TreeSet<>(Collections.reverseOrder());
		
		for(int i = 0; i < arr.length; i++) {
			for(int j = i + 1; j < arr.length; j++) {
				for(int l = j + 1; l < arr.length; l++) {
					Tset.add(arr[i] + arr[j] + arr[l]);
				}
			}
		}
		int cnt = 0;
		for(int x : Tset) {
			cnt++;
			if(cnt == k) return x;
		}
		
        return answer;
	}
	
	public static void main(String[] args){
		Main main  = new Main();
		Scanner sc =new Scanner(System.in);
		
		int n = sc.nextInt();
		int k = sc.nextInt();
		
		int[] arr = new int [n];
		for(int i = 0; i < n; i++) {
			arr[i] = sc.nextInt();
		}
		
		System.out.println(main.solution(arr, k));
		
		sc.close();
		return ;
	}
}

 

 

 

Comments