notes103 - Created By: Arthur Moy - [email protected] Lecture...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Created By: Arthur Moy - [email protected] Lecture Notes - January 23, 2002 Example of Algorithm using stacks: - computing the span of a stock price - the span of a stockprice for a certain day d is the number of previous consecutive days including d that the stock has been less than price at day d Simple Solution: - for each day find the previous day the stock was higher - subtract that day with current day + 1 class StockPrice{ double price; int span; } class StockExchange{ int n; //number of days StockPrice dayPrice[]; //assume price already added to dayPrice } void computeSpan() //Code a J--; } //Code c dayPrice[i].span = i-J; } Worst Case Scenario - The stock increases everyday. Code a ==> is executed n times Code b ==> is executed n squared times ( 0(n^2) ) Code c ==> is executed n times Highest Order (Complexity) = 0(n^2) Solution using a Stack
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
computeSpan(){ StackInt stack=new StackInt(); //Code a for(int i=0; i while(!stack.isEmpty && dayPrice [stack.top()].price <= dayPrice[i].price){ stack.pop(); } //Code c int n; //higher day if (stack.isEmpty()){ h = -1; //no previous higher day
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/02/2012 for the course CS 251 taught by Professor Staff during the Fall '08 term at Purdue University.

Page1 / 6

notes103 - Created By: Arthur Moy - [email protected] Lecture...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online