๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 11055_๊ฐ€์žฅ ํฐ ์ฆ๊ฐ€ํ•˜๋Š” ๋ถ€๋ถ„ ์ˆ˜์—ด

๋ฟŒ์•ผ._. 2024. 5. 10. 14:18

Silver II

๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/11055)

< ๊ฐ€์žฅ ํฐ ์ฆ๊ฐ€ํ•˜๋Š” ๋ถ€๋ถ„ ์ˆ˜์—ด >

 

๋ฌธ์ œ ํ’€์ด 

 

๊ฐ’์„ ์ฐจ๋ก€๋Œ€๋กœ ์‚ดํŽด๋ณด๋ฉฐ ์ฆ๊ฐ€ํ•˜๋Š”์ง€ ํŒ๋‹จํ•œ๋‹ค. ์ฆ๊ฐ€ํ•œ๋‹ค๋ฉด ํ•ฉ์ด ๋” ํฐ์ง€ ํŒ๋‹จํ•œ๋‹ค.

 

 my solution (Java)

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

public class _11055_ { // ๊ฐ€์žฅ ํฐ ์ฆ๊ฐ€ํ•˜๋Š” ๋ถ€๋ถ„ ์ˆ˜์—ด

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;

		int n = Integer.parseInt(bf.readLine());

		int arr[] = new int[n];
		int sum[] = new int[n];
		st = new StringTokenizer(bf.readLine());

		for (int i = 0; i < n; i++) {
			int num = Integer.parseInt(st.nextToken());
			arr[i] = num;
			sum[i] = num;
		}

		int result = sum[0];
		for (int i = 0; i < n - 1; i++) {
			for (int j = i + 1; j < n; j++) {
				if (arr[i] < arr[j] && sum[i] + arr[j] > sum[j]) {
					sum[j] = sum[i] + arr[j];
					result = Math.max(sum[j], result);
				}
			}
		}

		System.out.println(result);
	}
}
๋ณ€์ˆ˜)
n : ์ˆ˜์—ด์˜ ํฌ๊ธฐ
arr : ์ˆ˜์—ด ๊ฐ’
sum : ํ•ฉ
result : ํ•ฉ์ด ๊ฐ€์žฅ ํฐ ์ฆ๊ฐ€ํ•˜๋Š” ๋ถ€๋ถ„ ์ˆ˜์—ด์˜ ํ•ฉ

 

์ˆ˜์—ด์˜ ํฌ๊ธฐ n์„ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค. ์ˆ˜์—ด์˜ ํฌ๊ธฐ๋งŒํผ ์ˆ˜์—ด ๊ฐ’์„ ์ž…๋ ฅ๋ฐ›์•„ arr๊ณผ  sum์— ์ €์žฅํ•œ๋‹ค. ์ด์ค‘ for๋ฌธ์„ ์‚ฌ์šฉํ•˜์—ฌ ์ˆ˜์—ด์„ ํƒ์ƒ‰ํ•œ๋‹ค. ๋งŒ์•ฝ ๋น„๊ตํ•˜๋Š” ๊ฐ’์ด ํ˜„์žฌ ๊ฐ’๋ณด๋‹ค ํฌ๊ณ  ํ•ฉ๋„ ํฌ๋‹ค๋ฉด ๊ฐ’์„ ์—…๋ฐ์ดํŠธํ•œ๋‹ค. 

 

์ตœ์ข… ํ•ฉ์ด ๊ฐ€์žฅ ํฐ ์ฆ๊ฐ€ํ•˜๋Š” ๋ถ€๋ถ„ ์ˆ˜์—ด์˜ ํ•ฉ์„ ์ถœ๋ ฅํ•œ๋‹ค.

 

* ์ˆ˜์—ด์˜ ์ฒซ ๋ฒˆ์งธ ๊ฐ’์ด ์ •๋‹ต์ด ๋  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ result๋ฅผ sum[0] ๊ฐ’์œผ๋กœ ์ดˆ๊ธฐํ™”ํ•œ๋‹ค.