백준 20546번 : 기적의 매매법 | 자바 풀이

박지윤·2022년 7월 20일
0

Algorithm_Implementation

목록 보기
15/16

[ Solution ]

package implement20546;

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

public class Main {

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

        Scanner sc = new Scanner(System.in);
        int money = sc.nextInt();
        int[] chart = new int[14];

        for(int i = 0; i < 14; i++) {
            chart[i] = sc.nextInt();
        }

        int junhyeonResult = BNP(chart, money);
        int sungminResult = TIMING(chart, money);

        if(junhyeonResult > sungminResult) {
            System.out.println("BNP");
        }
        else if(junhyeonResult < sungminResult) {
            System.out.println("TIMING");
        }
        else {
            System.out.println("SAMESAME");
        }

    }

    static int BNP(int chart[], int money) {

        int count = 0;
        int lmoney = money;

        for(int i = 0; i < 14; i++) {
            int now = lmoney/chart[i];
            count += now;
            lmoney -= now * chart[i];
        }

        return lmoney + count * chart[13];
    }

    static int TIMING(int chart[], int money) {

        int count = 0;
        int lmoney = money;
        int upCount = 0;
        int downCount = 0;
        int yesterday = chart[0];

        for(int i = 1; i < 14; i++) {
            int today = chart[i];

            if(today > yesterday) {
                upCount++;
                downCount = 0;
            }
            else if(today < yesterday) {
                downCount++;
                upCount = 0;
            }
            else {
                upCount = 0;
                downCount = 0;
            }

            if(upCount == 3) {
                if(count != 0) {
                    lmoney += today * count;
                }
                upCount = 0;
                count = 0;
            }

            else if(downCount == 3) {
                int now = lmoney / today;
                count += now;
                lmoney -= now * today;
            }
        }

        return lmoney + count * chart[13];
    }
}

문제가 굉장히 길지만,, 원리는 단순하다

준현이는 돈이 있으면 무조건 최대한 많이 사고
성민이는 3일 연속 오르면 다음날 떨어질 것이라고 생각하고 가지고 있는 걸 모두 팔고,
3일 연속 내리면 다음날 오를 것이라고 생각하고 살 수 있는 최대한을 사는 것이다.

코드 구현하는 과정이 조금 귀찮긴 했지만,, 확실히 BNP와 TIMING 각각을 함수로 표현하는 것이 가독성도 훨씬 좋고 구현하기도 편리했다.

0개의 댓글