# Notes102 - Example of Algorithm Using Stacks CS 251 Course Notes for prepared by Jonathan Deutsch if you notice any inaccuracies please email

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

Example of Algorithm Using Stacks CS 251 Course Notes for January 23, 2002 prepared by Jonathan Deutsch if you notice any inaccuracies, please email [email protected] Computing the span of a stock price - The span of a stock price for a certain day (d) is the number of previous consecutive days (including d) that the stock has been less than the price at day d. Simple Solution - For each day, find the previous day the stock was higher - Subtract that day with the current day + 1 class StockPrice { double price; int span; } class StockExchange { int n; // # of days StockPrice dayPrice[]; // Assume price already added to day price void computeSpan() { A for(int i = 0; i < n; i++) A { A int j = i; A A // go back until j reaches a day where price is higher B B { B j--; B } B C dayPrice[i].span = i-j; } } } - The worst case is where the stock continuously grows - A is executed: N times = O(N) - B is executed: 1+2+3+4+. ..+N times = sum of i, from i=0 to n = O(N^2) - C is executed: N times = O(N) - The resulting complexity of this algorithm is O(N^2) Solution Using a Stack void computerSpan() { StackInt stack = new StackInt();

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

View Full Document
A for(int i = 0; i < n; i++) A { A // computer span for day i
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-West Lafayette.

### Page1 / 6

Notes102 - Example of Algorithm Using Stacks CS 251 Course Notes for prepared by Jonathan Deutsch if you notice any inaccuracies please email

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

View Full Document
Ask a homework question - tutors are online