[백준 17298] 오큰수 (스택)

문제

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

 

17298번: 오큰수

첫째 줄에 수열 A의 크기 N (1 ≤ N ≤ 1,000,000)이 주어진다. 둘째 줄에 수열 A의 원소 A1, A2, ..., AN (1 ≤ Ai ≤ 1,000,000)이 주어진다.

www.acmicpc.net

 

코드

package org.kyhslam.DoItAlgorithm.ch02;

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

public class p17298 {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();

        // 4
        // 3 5 2 7 > 5 7 7 -1

        // 9 5 4 8 > -1 8 8 -1
        int[] arr = new int[N];
        int[] ans = new int[N];

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


        Stack<Integer> stack = new Stack<>();

        stack.push(0);
        for (int i = 1; i < N; i++) {

            while (!stack.isEmpty() && arr[stack.peek()] < arr[i]) {
                ans[stack.pop()] = arr[i];
            }
            stack.push(i);
        }

        System.out.println("ans = " + Arrays.toString(ans));
        System.out.println("stack = " + stack);
    }
}

댓글

Designed by JB FACTORY