title: Determine if a sorted array contains a contiguous sequence that sums up to N
body: <p>I'm trying to write an algorithm that will return <code>True/False</code> whether a contiguous sequence in a <strong>sorted array</strong> that contains only positive integers, can sum up to <code>N</code>.</p>
  
  <p>For example:</p>
  
  <pre><code>Array = {  1, 2, 3, 4 };
  6 is good! 1 + 2 + 3 = 6
  8 is not good! 1 + 3 + 4 = 8, but it's not contiguous, since we skipped the 2.
  </code></pre>
  
  <p>This is what I have tried to do:</p>
  
  <pre><code>int[] arr = ...;
  int headIndex = 1, tailIndex = 0, sum = arr[0];
  
  while (sum != n)
  {
      if (sum &lt; n)
      {
          sum += arr[headIndex++];
      }
  
      if (sum &gt; n)
      {
          sum -= arr[tailIndex++];
      }
  }
  
  return sum == n;
  </code></pre>
  
  <p>Obviously the above does not work (In some cases it might get stuck in an infinite loop). Any suggestions?</p>
  
  <p>One thing I haven't mentioned earlier, and is very important- the algorithm's complexity must be low as possible.</p>