๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm

[SW Expert Academy] - (D3)4466. ์ตœ๋Œ€ ์„ฑ์ ํ‘œ ๋งŒ๋“ค๊ธฐ

by ์ฃผ๋ฐœ2 2020. 6. 13.
๋ฐ˜์‘ํ˜•

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AWOUfCJ6qVMDFAWg&categoryId=AWOUfCJ6qVMDFAWg&categoryType=CODE

 

SW Expert Academy

SW ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์—ญ๋Ÿ‰ ๊ฐ•ํ™”์— ๋„์›€์ด ๋˜๋Š” ๋‹ค์–‘ํ•œ ํ•™์Šต ์ปจํ…์ธ ๋ฅผ ํ™•์ธํ•˜์„ธ์š”!

swexpertacademy.com

 

์ฝ”๋“œ

import java.util.Arrays;
import java.util.Scanner;

public class Solution {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		
		int t = scan.nextInt();
		
		for(int tc=1; tc<=t; tc++) {
			int N = scan.nextInt();
			int K = scan.nextInt();
			int[] scores = new int[N];
			int sum = 0;
			
			for(int i=0; i<N; i++) {
				scores[i] = scan.nextInt();
			}
			
			Arrays.sort(scores);

			// K๊ฐœ์˜ ๊ณผ๋ชฉ์„ ์„ ํƒํ•˜๋ฏ€๋กœ, ๋”ํ• ๋•Œ๋งˆ๋‹ค -1์”ฉ ํ•˜๊ณ  0์ด๋ ๊ฒฝ์šฐ ํƒˆ์ถœ
			for(int i=scores.length-1; i>=0; i--) {
				sum += scores[i];
				K --;
				if(K == 0) {
					break;
				}
			}
			
			System.out.println("#" + tc + " " + sum);
			
		}
		
		scan.close();
	}

}

ํ’€์ด

 

์„ฑ์ ์ด ์ฃผ์–ด์ง€๊ณ  K๊ฐœ์˜ ๊ณผ๋ชฉ๋งŒ ์„ ํƒํ•ด์„œ ์–ป์„ ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€์ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•˜๋ฉด ๋œ๋‹ค.

๋ฐฐ์—ด์„ ์ •๋ ฌํ•ด์„œ ๋’ค์—์„œ ๋ถ€ํ„ฐ(๊ฐ’์ด ํฐ๊ฐ’๋ถ€ํ„ฐ) K๊ฐœ์ˆ˜๋งŒํผ ๋”ํ•œ๋‹ค.

 

 

+++

์Œ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ์ด๋ฏ€๋กœ ๊ฐ€์žฅ ํฐ ๊ฐ’์ด ๋’ค์—์„œ๋ถ€ํ„ฐ ์ •๋ ฌ๋˜๊ณ , ๋’ค์—์„œ๋ถ€ํ„ฐ ๋”ํ•˜๋‹ค๋ณด๋‹ˆ for๋ฌธ์•ˆ์— ๋ถˆํ•„์š”ํ•œ if๋ฌธ์ด ๋” ์ถ”๊ฐ€๋˜์—ˆ๋‹ค.

๋งŒ์•ฝ i๊ฐ’์ด 0๋ถ€ํ„ฐ๋ผ๋ฉด i=0; i<K ์™€ ๊ฐ™์ด ๊ฐ„๋‹จํ•˜๊ฒŒ ํ•  ์ˆ˜ ์žˆ๋‹ค. ์กฐ๊ธˆ๋งŒ ์ƒ๊ฐํ•ด๋ณด๋ฉด ๋’ค์—์„œ ๋ถ€ํ„ฐ ์ถœ๋ ฅํ•ด๋„ i๊ฐ’์„ 

๋ฐฐ์—ด์˜ ๊ธธ์ด์—์„œ K๊ฐ’์„ ๋บ€๋งŒํผ๋งŒ ์‹คํ–‰ํ•˜๋ฉด ๋™์ผํ•œ ๊ฒฐ๊ณผ์ด๋‹ค. ๋”ฐ๋ผ์„œ ๋‹ค์Œ ์ฝ”๋“œ๋„ ๋™์ผํ•˜๊ฒŒ ์ž‘๋™ํ•œ๋‹ค.

import java.util.Arrays;
import java.util.Scanner;

public class Solution {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		
		int t = scan.nextInt();
		
		for(int tc=1; tc<=t; tc++) {
			int N = scan.nextInt();
			int K = scan.nextInt();
			int[] scores = new int[N];
			int sum = 0;
			
			for(int i=0; i<N; i++) {
				scores[i] = scan.nextInt();
			}
			
			Arrays.sort(scores);

			// K๊ฐœ์˜ ๊ณผ๋ชฉ์„ ์„ ํƒํ•˜๋ฏ€๋กœ, ๋”ํ• ๋•Œ๋งˆ๋‹ค -1์”ฉ ํ•˜๊ณ  0์ด๋ ๊ฒฝ์šฐ ํƒˆ์ถœ
			for(int i=scores.length-1; i>=scores.length-K; i--) {
				sum += scores[i];
			}
			
			System.out.println("#" + tc + " " + sum);
			
		}
		
		scan.close();
	}

}

 

for๋ฌธ์—์„œ if๋ฌธ์„ ์ œ๊ฑฐํ•˜๊ณ , ์กฐ๊ฑด์—์„œ K๊ณผ๋ชฉ์˜ ๊ฐœ์ˆ˜๋งŒํผ๋งŒ ๋”ํ•˜๋„๋ก ๋ณ€๊ฒฝํ–ˆ๋‹ค.

			// K๊ฐœ์˜ ๊ณผ๋ชฉ์„ ์„ ํƒํ•˜๋ฏ€๋กœ, ๋”ํ• ๋•Œ๋งˆ๋‹ค -1์”ฉ ํ•˜๊ณ  0์ด๋ ๊ฒฝ์šฐ ํƒˆ์ถœ
			for(int i=scores.length-1; i>=scores.length-K; i--) {
				sum += scores[i];
			}

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€