Hackerrank | Maximum Element

133210·2021년 7월 26일
0

2020 문제풀이

목록 보기
12/14
post-thumbnail

https://www.hackerrank.com/challenges/maximum-element/problem

Problem

1 이면 stack에 push
2면 pop
3이면 현재 스택에 저장된 값 중 가장 큰 값 출력

Code

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int top = 0, max = 0;
int stack[1000000] = { 0 };

void push();
void pop();

int main() {
    int n;
    int type;
    int num;

    scanf("%d", &n);
    while (n--)
    {
        scanf("%d", &type);
        if (type == 1)
            push();
        else if (type == 2)
            pop();
        else
            printf("%d\n", max);
    }

    return 0;
}

void push()
{
    int i;
    scanf("%d", &i);
    top++;
    stack[top] = i;
    if (max < stack[top]) 	//최대값 찾는 과정
        max = stack[top];
}

void pop()
{
    int i;
    if (max == stack[top])
        max = 0;			//현재 나가는 값이 최대값이면 최대값=0
    top--;
    for (i = top; i >= 0; i--)	//다시 최대값 찾기
    {
        if (max < stack[i])
            max = stack[i];
    }
}

Result

0개의 댓글