Skip to main content

Stock Price Tracking

Say we have an array of values that represents the stock price of duckduckgo over time.


const stocks = [1, 0, 5, 14,  -1, 10];

How do we write a function that tells us what the biggest margin is? What is the optimal price that we can both buy and sell at? We cannot sell stock before we buy it. 

One approach requires iterating though each number and calculate the delta of every price in the future to ensure that we only make comparisons going forward in time. 

Here is an example

const stocks = [1, 0, 5, 14,  -1, 10 ];

const maximum = function(array) {
  let maximumStocks = array.forEach(delta);
  temp.sort(function(a, b){return a-b});
  return temp[temp.length -1]

let temp= [];

const delta = function(item, index, array) {
  // we want to calculate delta from 0
  // start with first one 
  let tempArray = array.slice(index) ;
     // calc deltas and add to temp
     for (i = 0; i < tempArray.length ; i++) {
     temp.push(tempArray[i] - tempArray[0]); 


This outputs 14 with this dataset. We can see that we can buy when the stock price was zero and would have made a tidy profit if we had sold when the price was at 14.


Add new comment

Filtered HTML

  • Web page addresses and email addresses turn into links automatically.
  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.