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:
- loop left right, find largest
kn1 + ... + nk <= target, setsum = n1 + ... + nk. if array sum smaller target, return false. - if
sum == target, done. if not, subarrayssumtargethaves.length < k, , begin element larger first one. kick out first sum:sum -= n1,leftend++. can go step 1, no need computekscratch.
since left end moves @ n times, , right end moves @ n times, algorithm has time complexity o(n), , constant space requirement.
Comments
Post a Comment