Saturday 28 October 2017

Maximum element in stack hacker rank solution in C


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

Solution

#include <stdio.h>
#include <stdlib.h>
int data[100000],top,max=0;
void push()
{
   int item;
   scanf("%d",&item);
   top++;
   data[top]=item;
   if(max < data[top])
        max = data[top];
}

void pop()
{
    int i;
    if(max == data[top])
        max=0;
    top--;
    for(i= top;i>=0;i--)
        if(max < data[i])
            max = data[i];
}
int main()
{
    int t,n,choice;
    top = -1;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&choice);
        switch(choice)
        {
            case 1 : push();
                     break;
            case 2:  pop();
                     break;
            case 3: printf("%d\n",max);
                    break;
        }
    }
    return 0;

}

===============(or)  using structure=======================
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

struct stack
{
    int data[100000];
    int top;
}st;
int max=0;
void push()
{
    int item;
    scanf("%d",&item);
    st.top++;
    st.data[st.top]=item;
    if(max<st.data[st.top])
        max=st.data[st.top];
   
}
void pop()
{
    int i;
    if(max == st.data[st.top])
        max=0;
    st.top--;
     for(i=st.top;i>=0;i--)
        if(max<st.data[i])
            max=st.data[i];
}

int main()
{
    int t,n,choice;
    st.top = -1;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&choice);
        switch(choice)
        {
            case 1 :push();
            break;
            case 2:pop();
            break;
            case 3: printf("%d\n",max);
            break;
        }
    }
    return 0;
}




4 comments:

  1. Is it possible to do without using structures

    ReplyDelete
    Replies
    1. Yes you can. Just remove the struct keyword and remove st.

      Delete
  2. thank you so much brother or sister.

    ReplyDelete
  3. mam where r u working now mam

    i am also studying in klu

    ReplyDelete