• Home
  • About
    • Ryureka Moment photo

      Ryureka

      Sin Prisa, Sin Pausa

    • About Me
    • Facebook
    • Github
    • Youtube
  • Projects
  • Posts
    • Posts
    • ProblemSolvings
    • Tags
    • Blog
    • Examples
  • ProblemSolving
    • ProblemSolving
    • BOJ
    • Programmers
    • SWEA
    • LeetCode
  • FrontEnd
    • FrontEnd
    • HTML
  • BackEnd
    • BackEnd
    • Server
      • Server
      • Spring
      • NodeJS
    • DataBase
      • DataBase
      • MySQL
      • MongoDB
  • Programming
    • Programming
    • Java
    • JS
    • Python
    • CleanCode
  • ComputerScience
    • DataStructure
    • Algorithm

[BOJ] 17298. 오큰수

15 Apr 2026

Reading time ~1 minute

  • 풀이

풀이

import java.util.Scanner;
import java.util.Stack;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		
		int[] arr = new int[N];
		
		for(int i = 0; i < arr.length; i++) {
			arr[i] = sc.nextInt();
		}
		
		Stack<Integer> stack = new Stack<>();
		Stack<Integer> answerStack = new Stack<>();
		StringBuilder sb = new StringBuilder();
		for(int i = arr.length - 1; i >= 0; i--) {
			while(!stack.isEmpty() && arr[stack.peek()] <= arr[i]) {
				stack.pop();				
			}
			if(stack.isEmpty()) answerStack.push(-1);
			else answerStack.push(arr[stack.peek()]);
			stack.push(i);						
		}
		
        while(!answerStack.isEmpty()) {
			sb.append(answerStack.pop()+" ");
		}
		
		System.out.println(sb);
	}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Stack;
import java.util.StringTokenizer;

public class Main {
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		int N = Integer.parseInt(bf.readLine());
		int[] arr = new int[N];
		
		StringTokenizer st = new StringTokenizer(bf.readLine());
		
		for(int i = 0; i < arr.length; i++) {
			arr[i]=Integer.parseInt(st.nextToken());		
		}
		
		Stack<Integer> stack = new Stack<>();
		Stack<Integer> answerStack = new Stack<>();
		
		for(int i = arr.length - 1; i >= 0; i--) {
			while(!stack.isEmpty() && arr[stack.peek()] <= arr[i]) {
				stack.pop();				
			}
			if(stack.isEmpty()) answerStack.push(-1);
			else answerStack.push(arr[stack.peek()]);
			stack.push(i);						
		}
		
		while(!answerStack.isEmpty()) {
			bw.write(answerStack.pop()+" ");
		}
		bw.flush();
		bw.close();	
		
	}
}


스택 Share