java - optimised algorithm to find maximum value in stack -


  stack<integer> st= new stack<integer>();   int max=(int) st.peek();   int top=0;   for(integer loopval:st)   {      if(max<loopval)          max=loopval;   }   system.out.println(max); 

this code, finds maximum value in stack, working fine, wish optimize performance can handle large stack. can suggest better algorithm?

the complexity of algorithm o(n) - linear. need process elements before finding maximum. given data structure won't better complexity.

the 1 option have sorted data structure, elements ordered. allow maximum o(1) complexity, sorting takes o(n*log(n)) makes no sense if need max element only.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -