SSAFY/SWEA

[SWEA] 9229 : 한빈이와 spot Mart

믕비 2023. 5. 2. 18:42

https://swexpertacademy.com/main/code/problem/problemDetail.do?problemLevel=3&contestProbId=AW8Wj7cqbY0DFAXN&categoryId=AW8Wj7cqbY0DFAXN&categoryType=CODE&problemTitle=&orderBy=SUBMIT_COUNT&selectCodeLang=ALL&select-1=3&pageSize=10&pageIndex=2 

 

SW Expert Academy

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

swexpertacademy.com

주어진 수들 중 합한 값이 기준보다 낮으면서 최대의 값을 가지는 조합을 구하는 문제 중 조합을 이루는 수를 2개만 고르는 문제는 굉장히 쉽게 풀 수 있게 됐다. 

 

내 코드

메모리 : 23180 KB

시간 : 138 ms

코드길이 : 1195 B

 

[내 코드]

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

public class Solution {
	static int N;
	static int M;
	static int[] gram;
	static int result;

	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		StringTokenizer st;
		
		int T = Integer.parseInt(br.readLine());
		for(int t = 1; t <= T; t++) {
			sb.append('#').append(t).append(' ');
			
			st = new StringTokenizer(br.readLine());
			N = Integer.parseInt(st.nextToken());
			M = Integer.parseInt(st.nextToken());
			gram = new int[N];
			result = -1;
			
			st = new StringTokenizer(br.readLine());
			for(int n = 0; n < N; n++) {
				gram[n] = Integer.parseInt(st.nextToken());
			}
			
			for(int i = 0; i < N; i++) {
				choiceTwo(i);
			}
			
			sb.append(result).append('\n');
		}
		System.out.print(sb);
	}
	
	public static void choiceTwo(int first) {
		int gramOfTwo = gram[first];
		for(int i = first + 1; i < N; i++) {
			int temp = gramOfTwo + gram[i];
			if(temp <= M)
				result = Math.max(result, temp);
		}
		return;
	}
}