[JAVA] SWEA (D2) 1859. 백만 장자 프로젝트

AIR·2023년 11월 16일
0

링크

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


문제 설명

(정답률 32.55%)
다음과 같은 조건 하에서 사재기를 하여 최대한의 이득을 얻도록 도와주자.

  1. 원재는 연속된 N일 동안의 물건의 매매가를 예측하여 알고 있다.
  2. 당국의 감시망에 걸리지 않기 위해 하루에 최대 1만큼 구입할 수 있다.
  3. 판매는 얼마든지 할 수 있다.

예를 들어 3일 동안의 매매가가 1, 2, 3 이라면 처음 두 날에 원료를 구매하여 마지막 날에 팔면 3의 이익을 얻을 수 있다.


입력 예제

3
3
10 7 6
3
3 5 9
5
1 1 3 1 2


출력 예제

#1 0
#2 10
#3 5


정답 코드

각 매매가에 대해서 반복을 하며 3가지의 경우로 나눈다.

  1. 매매가가 최대 값이 아닐 때 구매
  2. 매매가가 최대 값이고 이전에 구매 내역이 존재하면 매매가에 판매
  3. 매매가가 최대 값이나 이전에 구매한 적이 없으면 패스
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

class SWEA {
    public static void main(String[] args) throws IOException {

        System.setIn(new FileInputStream("src/input.txt"));
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;

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

        for (int test_case = 1; test_case <= T; test_case++) {

            int N = Integer.parseInt(br.readLine());
            int[] price = new int[N];	//각 날의 매매가
            long bought = 0;			//총 구매 금액
            long count = 0;				//구매 횟수
            long answer = 0;
            st = new StringTokenizer(br.readLine());
			
            //각 날의 매매가를 입력값으로 할당
            for (int i = 0; i < N; i++) {
                price[i] = Integer.parseInt(st.nextToken());
            }
			//최대 매매가
            int max = Arrays.stream(price).max().orElse(0);
			
            //모든 매매가에 대해 반복한다
            for (int i = 0; i < N; i++) {
            	//매매가가 최대 금액이고 이전에 구매한 적이 있을 때
                if (price[i] == max && bought != 0) {
                    answer += max * count - bought;
                    price[i] = 0;
                    max = Arrays.stream(price).max().orElse(0);
                    bought = 0;
                    count = 0;
                    continue;
                }
                //매매가가 최대 금액이나 이전에 구매한 적이 없을 때
                if (price[i] == max && bought == 0) {
                    price[i] = 0;
                    max = Arrays.stream(price).max().orElse(0);
                    continue;
                }
                //위 조건에 해당되지 않을 때 매매가에 구매
                bought += price[i];
                //구매한 날은 최대값 계산에서 제외시키기 위해 0 할당
                price[i] = 0;
                count++;
            }


            System.out.println("#" + test_case + " " + answer);
        }
    }
}

정리

크게 어렵진 않은 문제였다.
다만 구매 금액을 int로 선언하면 안된다.
int의 최대값은 21억이지만
N의 최대값이 100만, 매매가의 최대값은 1만이므로
최대값은 100억이 나온다.
그래서 long으로 선언해야 통과할 수 있었다.

그리고 int배열에서 stream을 사용하여 최대값을 구하는 방법을 알게되었다.

int[] array = {1, 3, 5, 2, 7, 4};
int max = Arrays.stream(array).max().orElse(0);
// max = 7

//getAsInt() 메서드도 가능하지만 배열이 비어있는 경우 예외가 발생한다.
int max2 = Arrays.stream(array).max().getAsInt();
profile
백엔드

0개의 댓글