Post

[BaekJoon] 30804번 - 과일 탕후루 [Java][C++]

[BaekJoon] 30804번 - 과일 탕후루 [Java][C++]

문제 링크


1. 문제 풀이


과일 탕후루에서 막대의 앞쪽과 뒤쪽에서 몇 개의 과일을 빼서 두 종류 이하의 과일만 남기는 문제로 투 포인터를 활용하면 해결할 수 있다. 두 포인터 사이에 위치한 과일들이 막대에 꽂혀있는 과일들로 간주하면 앞쪽과 뒤쪽에서 몇 개의 과일을 뺀 것을 다룰 수 있으며 과일의 종류가 $10$ 미만의 자연수들만 있으므로 카운팅 배열을 활용해서 두 포인터 내 과일의 종류의 수를 세주었다.


2. 코드


1. 풀이 [Java]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.io.*;
import java.util.*;

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

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

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

        int left = 0;
        int right = 0;
        int[] cntArr = new int[10];
        int typeCnt = 0;
        int max = 0;

        while (true) {
            if (typeCnt > 2) {
                cntArr[arr[left]]--;
                if (cntArr[arr[left]] == 0) typeCnt--;
                left++;
            } else {
                if (cntArr[arr[right]] == 0) typeCnt++;
                cntArr[arr[right]]++;
                right++;
            }

            if (typeCnt <= 2) max = Math.max(max, right - left);

            if (right == N && typeCnt <= 2) break;
        }

        System.out.println(max);
    }
}


2. 풀이 [C++]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;

    vector<int> v(n);
    for (int& x : v) cin >> x;

    int l = 0;
    int r = 0;
    int cntArr[10] = {};
    int type = 0;
    int mx = 0;

    while (true) {
        if (type > 2) {
            cntArr[v[l]]--;
            if (cntArr[v[l]] == 0) type--;
            l++;
        } else {
            if (cntArr[v[r]] == 0) type++;
            cntArr[v[r]]++;
            r++;
        }

        if (type <= 2) mx = max(mx, r - l);

        if (r == n && type <= 2) break;
    }

    cout << mx;
}

This post is licensed under CC BY 4.0 by the author.