title: Find maximum difference in array
body: <p>I'm working on an algorithm to return the <strong>difference</strong> of any pair of numbers, <strong>such that the larger integer in the pair occurs at a higher index (in the array) than the smaller integer</strong>. </p>
  
  <p>Examples... </p>
  
  <p>Array: [2, 3, 10, 2, 4, 8, 1]</p>
  
  <p>Solution: 10 - 2 = 8</p>
  
  <p>Output: 8</p>
  
  <hr>
  
  <p>Array: [7, 9, 5, 6, 3, 2]</p>
  
  <p>Solution: 9 - 7 = 2</p>
  
  <p>Output: 2</p>
  
  <hr>
  
  <p>Here is what I have but it doesn't work for all tests...</p>
  
  <pre><code>var a = [22, 2, 4, 5, 6, 444, 1, 666];
  
  // declare variables
  var minNumber = a[0],                   // initilize to first element
      maxNumber = a[0],                   // --- ^
      minNumberIndex = 0,                 // min index
      maxNumberIndex = a.length - 1;      // max index
  
  // loop through each element in array
  for(i = 0; i &lt; a.length; i++) {
  
      // find min
      if (a[i] &lt; minNumber &amp;&amp; i &lt; maxNumberIndex) {
          minNumber = a[i];
          minNumberIndex = i;
      }
  
      // find max
      if (a[i] &gt;= maxNumber &amp;&amp; i &gt; minNumberIndex) {
          maxNumber = a[i];
          maxNumberIndex = i;
      }
  }
  
  // return results
  console.log("max: \t" + maxNumber);
  console.log("min: \t" + minNumber + "index: " + minNumberIndex);
  console.log(maxNumber - minNumber);  
  </code></pre>
  
  <p>Please help!</p>