R

E

A

C

T

O

xamples 

epeat

ode

pproach

ptimize

est

{Stock Picker}

The Question

 Breakdown

  1. Realize you can't just do the max stock price - min stock price #becuase-time
  2. Solve it with brute force
  3. Solve it with cleverness

1. Realize you can't just do the max stock price - min stock price #becuase-time

To make the highest profit, you need to buy at the lowest price and sell at the highest price where the lowest price happens before the highest price. So you can't just find the highest and lowest price for the day and return their difference because its possible that the highest price was at 9:00am and the lowest price was two hours later at 11:00am.

2. solve it with brute force 

We can solve this problem with brute force by using nested looping. 

Keep Track Of

- The greatest difference between a two prices

Loop over 

- The array of stock prices and then for each element in that array loop over the array again looking for prices that occurred after the element you are currently looking at 

The problem with this solution 

- Because you loop over the whole array again for each element, your time is O(n^2) ... not good. Better times would be O(log(n), O(nlog(n)), or O(n).

3. Solve it with cleverness

Our curent brute force solution takes O(n^2) time. Better times would be O(log(n)) and O(n). An O(log(n)) time happens time happens when you can keep splitting up a dataset to find a thing instead of looping over the whole dataset a bunch of times. Think finding a number in a phonebook given a name. We can't solve this problem by dividing up the array over an over so it looks like our solution will be O(n) ... which means we are looping over a dataset only once. But how can we do this with just one loop O(n) time instead of a nested loop O(n^2) time???????  

3. Solve it with cleverness

Keep Track Of

- Our minPrice so far

- Our maxProfit so far

Each time check to see if

- We have hit a new min price

-  Buying at the current minPrice and selling at the current price would give us a new maxProfit 

- If we get a higher value than maxProfit set maxProfit to that value, otherwise move to the next element

3. Solve it with cleverness

Python Solution (python is cool!!)

3. Solve it with cleverness

JavaScript Solution

3. Solve it with cleverness

Have a repl.it

Have a repl.it

Conclusion  

Reacto:Stock Picker

By Benjamin Conant

Reacto:Stock Picker

  • 607
Loading comments...

More from Benjamin Conant