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
Post a Comment