SWE 9229ハンビンとSpot Markt


これは条件によってビスケットを2パック選ぶ問題です.
したがって,2のfor文を用いて完全検索を行うと,答えを容易に見つけることができる.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;

public class Solution {
	static BufferedReader br;
	static BufferedWriter bw;
	static StringTokenizer st;

	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		bw = new BufferedWriter(new OutputStreamWriter(System.out));
		int T = Integer.parseInt(br.readLine());
		for (int tc = 1; tc <= T; tc++) {
			int max_weight = -1, tmp;
			st = new StringTokenizer(br.readLine(), " ");
			int N = Integer.parseInt(st.nextToken());
			int M = Integer.parseInt(st.nextToken());
			st = new StringTokenizer(br.readLine(), " ");
			int[] snack_Weight = new int[N];
			for (int i = 0; i < N; i++) {
                tmp = Integer.parseInt(st.nextToken());
				if(tmp < M) {
					snack_Weight[i] = tmp;
				}else {
					i--;
					N--;
				}
			}	
			for (int i = 0; i < N - 1; i++) {
				for (int j = i + 1; j < N; j++) {	
					tmp = snack_Weight[i] + snack_Weight[j];
					if (tmp <= M && tmp > max_weight) {
						max_weight = tmp;
						if(max_weight == M) break; 
					}
				}
				if(max_weight == M) break; 
			}

			bw.write(String.format("#%d ", tc));
			bw.write(String.format("%d\n", max_weight));
		}
		bw.flush();
		bw.close();
	}
}