[코딩테스트][백준] 🔥 백준 30804번 "과일 탕후루" 문제: Python과 Java로 완벽 해결하기! 🔥

김상욱·2024년 8월 14일
post-thumbnail

문제 링크

https://www.acmicpc.net/problem/30804

🕒 Python 풀이시간: 40분

n = int(input())
arr = list(map(int, input().split()))

ans = 0
left = 0
count = {}
distinct_count = 0

for right in range(n):
    if arr[right] in count:
        count[arr[right]] += 1
    else:
        count[arr[right]] = 1
        distinct_count += 1
    
    while distinct_count > 2:
        count[arr[left]] -= 1
        if count[arr[left]] == 0:
            del count[arr[left]]
            distinct_count -= 1
        left += 1
    
    ans = max(ans, right - left + 1)

print(ans)

🕒 Java 풀이시간: 20분

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

// The main method must be in a class named "Main".
class Main {

    static int N;
    static int[] arr;
    
    public static void main(String[] args) throws IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st=new StringTokenizer(br.readLine());

        N=Integer.parseInt(st.nextToken());
        arr=new int[N];

        st=new StringTokenizer(br.readLine());
        for(int i=0;i<N;i++){
            arr[i]=Integer.parseInt(st.nextToken());
        }

        int answer=1;
        int typeCnt=1;
        int[] counter=new int[10];
        int cnt=1;
        counter[arr[0]]++;
        int sIdx=0;
        int eIdx=0;
        while(true){
            if(typeCnt>2){
                int nowType=arr[sIdx];
                counter[nowType]--;
                cnt--;
                if(counter[nowType]==0){
                    typeCnt--;
                }
                sIdx++;
            }else{
                if(answer<cnt)answer=cnt;
                eIdx++;
                if(eIdx>=N)break;
                int nextType=arr[eIdx];
                counter[nextType]++;
                cnt++;
                if(counter[nextType]==1){
                    typeCnt++;
                }
            }
        }
        System.out.println(answer);
    }
}

과일 탕후루의 길이 최대화 🍡🍏🍌

과일 탕후루를 만드는 과정에서 N개의 과일이 존재할 때, 두 종류로 이하로 이루어진 탕후루 중에서 가장 많은 갯수에 탕후루의 과일의 갯수를 구하는 문제이다.

탕후루는 연속되어야 하기 때문에 각 구간에 한해서 일회 순환으로 투포인터를 사용할 수 있다. 오른쪽으로 진행하면서 과일의 종류가 다르면 종류를 추가하고 각 종류의 갯수를 늘리면 된다. 이렇게 늘려가면서 진행을 하던 중 종류가 2가지가 넘어가면 왼쪽에서 반대로 종류가 2가지가 될 때까지 줄이면서 제외시키면 된다. 이렇게 진행하면서 각 경우의 길이를 정답으로 최대값을 찾는 형태로 갱신시키면 된다.

이렇게 Python과 Java로 백준의 "과일 탕후루" 문제를 해결해보았습니다. 코드와 개념 설명을 참고하여 문제를 해결하는 데 도움이 되셨길 바랍니다! 😊

0개의 댓글