This problem can be solved using simple encoding technique. We should use the minimum element to get the next minimum element.Here is a solution which uses O(1) space.PUSH(elem) Operation: In this process we are keeping minimum element on the top of the stack at any given time. And encoding(i.e elem-min) the actual data with minimum and storing. Whenever there is a change in cur minimum data stored in the stack will be negative. This property will be used while poping the elements to find the next minimum. We can define it as shown below. if stack is empty. Store the element twice Else CurMin = POP(); Take difference between elem and Curmin and push it on to stack. Push the least of elem and CurMin on to stack.
POP() Operation: POP process is bit tricky. If minimum is not changing (i.e elements are positive on stack) then return the element + curMin(sitting on stack). If you see a negative stack element then it means there was a shift of curMin (or minimum element is the one which is being popped). In this case we take the current minimum and return it as popped element. We find the new minimum (as current minimum is popped out) by computing curMin-element and push it on top of stack as minimum element. We can summarize it as shown below.curMin = pop();element = pop(); If element is negative then return curMin and push curMin-element on to stack. Else push curMin on to stack and return element + curMin.
FindMin():
This is trivial operation as we are storing minimum element on the top of the stack at any given time. So we pop it and return to the caller. FindMin() steps will be...min=pop();push(min);return min;
Categories
FollowersBlog Archive
Jobs
Find more freelance jobs
|
Tuesday, August 11, 2009
Subscribe to:
Post Comments (Atom)
|
Popular Posts
|
No comments:
Post a Comment