[백준] 간식 파티 (자바)

HeavyJ·2023년 4월 16일
0

백준

목록 보기
8/14

간식 파티

풀이 방법

오름차순으로 가장 큰 합을 가지는 DP 배열을 만드는 문제다

  1. 초기 DP 배열 값은 입력된 배열 값과 동일하게 설정
  2. 이중 for문으로 오름차순을 가지는 배열값(arr[i])이 나오면 dp[i] = Math.max(dp[i], dp[j] + arr[i])

구현 코드

import java.io.*;
import java.util.*;

import java.lang.*;

public class Main{

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int num = Integer.parseInt(br.readLine());

        int[] arr = new int[num];
        int[] dp = new int[num];


        for (int i = 0; i < num; i++){
            arr[i] = Integer.parseInt(br.readLine());
        }

        for (int i = 0; i < num ; i++){
            dp[i] = arr[i];
            for (int j = 0; j < i; j++){
                if (arr[i] > arr[j]){
                    dp[i] = Math.max(dp[i], dp[j] + arr[i]);
                }
            }
        }

        Arrays.sort(dp);

        bw.write(dp[num-1]+"");

        bw.flush();
        br.close();
        bw.close();
    }


}
profile
There are no two words in the English language more harmful than “good job”.

3개의 댓글

comment-user-thumbnail
2023년 4월 17일

감사합니다. 참고해서 해봤는데 혹시 출력 할 때 +"" 를 넣어야 출력이 되는데 이유가 무엇인가요?ㅠ

1개의 답글
comment-user-thumbnail
2023년 4월 17일

bw.write가 단일 출력일 경우에도 scaner보다 성능이 좋나요? 이게 궁금하네요!

답글 달기