algorithm - Determine if a sorted array contains a contiguous sequence that sums up to N -


i'm trying write algorithm return true/false whether contiguous sequence in sorted array contains positive integers, can sum n.

for example:

array = {  1, 2, 3, 4 }; 6 good! 1 + 2 + 3 = 6 8 not good! 1 + 3 + 4 = 8, it's not contiguous, since skipped 2. 

this have tried do:

int[] arr = ...; int headindex = 1, tailindex = 0, sum = arr[0];  while (sum != n) {     if (sum < n)     {         sum += arr[headindex++];     }      if (sum > n)     {         sum -= arr[tailindex++];     } }  return sum == n; 

obviously above not work (in cases might stuck in infinite loop). suggestions?

one thing haven't mentioned earlier, , important- algorithm's complexity must low possible.

this sketch:

  1. loop left right, find largest k n1 + ... + nk <= target, set sum = n1 + ... + nk. if array sum smaller target, return false.
  2. if sum == target, done. if not, subarray s sum target have s.length < k, , begin element larger first one. kick out first sum: sum -= n1, leftend++. can go step 1, no need compute k scratch.

since left end moves @ n times, , right end moves @ n times, algorithm has time complexity o(n), , constant space requirement.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -