Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

21.03.22 - [BOJ] 17298. 오큰수 #33

Closed
suhyunsim opened this issue Mar 11, 2021 · 0 comments
Closed

21.03.22 - [BOJ] 17298. 오큰수 #33

suhyunsim opened this issue Mar 11, 2021 · 0 comments
Assignees
Labels
골드 BOJ - 골드 스택 stack 실패 시도했지만 맞지 못한 문제

Comments

@suhyunsim
Copy link
Owner

suhyunsim commented Mar 11, 2021

문제

핵심 아이디어

  • 시간초과 조심
  • Stack 활용해서 O(N)으로 풀이
  • 스택에 인덱스를 넣는게 포인트

참고: 블로그

어려운 점, 실수

  • 이중 for문으로 풀고 시간초과 남

풀이

package main.java.com.poogle.BOJ.Q17298;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Stack;

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 n = Integer.parseInt(br.readLine());
        int[] answer = new int[n];
        int[] arr = new int[n];
        Stack<Integer> stack = new Stack<>();

        String[] tmp = br.readLine().split(" ");
        for (int i = 0; i < n; i++) {
            arr[i] = Integer.parseInt(tmp[i]);
        }

        stack.push(0);
        for (int i = 1; i < n; i++) {
            if (stack.isEmpty()) {
                stack.push(i);
            }
            while (!stack.isEmpty() && arr[stack.peek()] < arr[i]) {
                answer[stack.pop()] = arr[i];
            }
            stack.push(i);
        }
        while (!stack.isEmpty()) {
            answer[stack.pop()] = -1;
        }
        for (int i : answer) {
            bw.write(i + " ");
        }
        bw.write("\n");
        bw.flush();
    }

}
@suhyunsim suhyunsim added 골드 BOJ - 골드 스택 stack labels Mar 11, 2021
@suhyunsim suhyunsim added this to the 3월 2주 차 milestone Mar 11, 2021
@suhyunsim suhyunsim self-assigned this Mar 11, 2021
@suhyunsim suhyunsim changed the title 21.03.12 - [BOJ] 17298. 오큰수 21.03.22 - [BOJ] 17298. 오큰수 Mar 22, 2021
@suhyunsim suhyunsim modified the milestones: 3월 2주 차, 3월 4주 차 Mar 22, 2021
@suhyunsim suhyunsim added the 실패 시도했지만 맞지 못한 문제 label Jan 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
골드 BOJ - 골드 스택 stack 실패 시도했지만 맞지 못한 문제
Projects
None yet
Development

No branches or pull requests

1 participant