title: Difference between elements in one array in Java
body: <p>I'm learning Java and I trying to construct a method for my homework. It takes as argument an <code>Array</code> and returns the difference between its elements (as absolute value).</p>
  
  <p>For example:  array {7,8,5,7,2} </p>
  
  <p>the difference between elements 0 and 1 is 1 (=7−8)</p>
  
  <p>the difference between elements 1 and 2 is 3 (=8−5)</p>
  
  <p>the difference between elements 2 and 3 is 2 (=5-7)</p>
  
  <p>the difference between elements 3 and 4 is 5 (=7−2)</p>
  
  <p>the difference between elements 4 and 0 is 5 (=2-7)</p>
  
  <p>If there are multiple candidates the method will return the one with the greatest index. In this example, the last one. If the <code>array</code> is empty, then the method must return <code>−1</code>.</p>
  
  <p>I have some problems in my code (as you can see) and the biggest one is that my method returns only the last <code>diff</code> and not the biggest one with the higher index. Can someone help me? I'm not figuring out how to solve this problem.</p>
  
  <pre><code>public static int MaxDiff(int[] array){
  
          int diff = 0;
  
          if (array.length == 0){   // Checks for empty array
              return -1;
          }
  
          for (int i = 0; i &lt;= array.length; ++i){
  
              if(i == array.length){
                  diff = Math.abs(array[i] - array[0]);
              } else {
                  diff = Math.abs(array[i] - array[i+1]); // Mistake. Can be
                                                          // bigger than array
              }
          }
  
          return diff;
      } 
  </code></pre>