title: Longest subArray with no more than two distinct values that differ by no more than 1
body: <p>Given an array of integers what is the length of the longest subArray containing no more than two distinct values such that the distinct values differ by no more than 1</p>
  
  <p>For Example:</p>
  
  <p>arr = [0, 1, 2, 1, 2, 3] -> length = 4;  [1,2,1,2]</p>
  
  <p>arr = [1, 2, 3, 4, 5] -> length = 2;  [1,2]</p>
  
  <p>arr = [1, 1, 1, 3, 3, 2, 2] -> length = 4;  [3,3,2,2]</p>
  
  <p>I have such code</p>
  
  <pre><code> public static int longestSubarray(List&lt;Integer&gt; arr) {
          int max = 0;
          Set&lt;Integer&gt; set = new HashSet&lt;&gt;();
          int i = 0;
          int j = 1;
          while (i &lt; arr.size() - 1) {
              set.add(arr.get(i));
              while (j &lt; arr.size() &amp;&amp; Math.abs(arr.get(i) - arr.get(j)) &lt; 2) {
                  if (!set.contains(arr.get(j))) {
                      if (set.size() == 2) {
                          break;
                      } else {
                          set.add(arr.get(j));
                      }
                  }
                  ++j;
              }
              max = Math.max(max, j - i);
              j = ++i + 1;
              set.clear();
          }
          return max;
      }
  </code></pre>
  
  <p>Can there be a better solution?</p>