You are viewing a single comment's thread. Return to all comments →
This solution is wrong as a C\C++ solution. I am not sure how it passes all test. You need 2 stacks for this.
Algorithm is explained here: http://algorithms.tutorialhorizon.com/track-the-maximum-element-in-a-stack/
Here is my solution which is mapped off of the website provided above and it passes all test cases. The website is very good visual example:
auto query_type = 0; auto n = 0; int insert_element = 0; int max_index = 0; int max_element = 0;
stack<int> stack_list; stack<int> max_list; cin >> n; for( auto i = 0; i < n;i++ ) { cin >> query_type; switch(query_type) { case 1: cin >> insert_element; if(stack_list.empty()) { stack_list.push(insert_element); max_list.push(insert_element); } else{ if(insert_element > max_list.top()) { max_list.push(insert_element); }else { max_list.push(max_list.top()); } stack_list.push(insert_element); } break; case 2: if(!stack_list.empty()) { stack_list.pop(); max_list.pop(); } break; case 3: cout << max_list.top() << "\n"; default: break; } }
Seems like cookies are disabled on this browser, please enable them to open this website
Maximum Element
You are viewing a single comment's thread. Return to all comments →
This solution is wrong as a C\C++ solution. I am not sure how it passes all test. You need 2 stacks for this.
Algorithm is explained here: http://algorithms.tutorialhorizon.com/track-the-maximum-element-in-a-stack/
Here is my solution which is mapped off of the website provided above and it passes all test cases. The website is very good visual example:
auto query_type = 0; auto n = 0; int insert_element = 0; int max_index = 0; int max_element = 0;