Algorithm to find a consecutive sub-sequence whose sum would be a asked number M from a sequence of numbers in O(n)

南笙酒味 提交于 2019-12-14 02:54:38

问题


Hi I have been trying to solve this problem for some time now. Lets say we have an array of positive numbers and we were given a value M. Then our goal is to find if there is a consecutive sub sequence in the array of positive numbers such that the sum of the sequence is exactly equal to sum M. If A[1],A[2],....A[n] is an array then we have to find if there exist i and j such that A[i]+...+A[j] = M. I am trying to get the O(n) solution using greedy approach.


回答1:


I believe you can solve this in linear time with a pointer chasing algorithm.

Here's the intuition. Start off a pointer at the left side of the array. Keep moving it to the right, tracking the sum of the elements you've seen so far, until you either hit exactly M (done!), your total exceeds M (stop for now, adding in more elements only makes it worse), or you hit the end of the array without reaching at least M (all the elements combined are too small). If you do end up in a case where the sum exceeds M, you can be guaranteed that no subarray starting at the beginning of the array adds up to exactly M, since you tried all of them and they were either too small or too big.

Now, start a second pointer at the first element and keep advancing it forward, subtracting out the current element, until you either get to exactly M (done!), you reach the first pointer (stop for now), or the total drops below M (stop for now). All the elements you skipped over with this pointer can't be the starting point of the subarray you're looking for. At this point, start marching the first pointer forward again.

Overall, each pointer advances at most n times and you do O(1) work per step, so this runs in time O(n). Plus, it uses only O(1) space, which is as good as it's going to get!




回答2:


This is a standard two pointer problem. First of all, create an array, prefix that will store the prefix sum of the given array, say arr.

So

prefix[i] = arr[1] + .. + arr[i]

Start with two pointers, lower and upper. Initialize them as

lower = 0
upper = 1

(Note: Initialize prefix[0] to 0)

Now, try to understand this code:

lower = 0, upper = 1;
while(upper <= n) { // n is the number of elements
  if(prefix[upper] - prefix[lower] == m) {
    return true;
  } else if(prefix[upper] - prefix[lower] > m) {
    lower++;
  } else {
    upper++;
  }
}
return false;

Here we are using the fact that the array consists of positive integers, hence prefix is increasing




回答3:


Assume that the subarray with indices X ≤ i < Y might be the solution.

You start with X = 1, Y= 1, sum of elements = 0.

As long as the sum is less than M, and Y <= n, increase the sum by array [Y] and replace Y with Y + 1.

If the sum is equal to M, you found a solution.

If the sum is less than M, you remove array elements at the start: As long as the sum is greater than M, subtract array [X] from the sum and replace X with X + 1. If the sum became equal to M, you have a solution. Otherwise you start with the first loop.




回答4:


(edited: see templatetypedef's comment)

Use the two indices approach: increase the lower index if subsequence too small otherwise increase higher index.

Example:

void solve(int *a, int n, int M) {
    if (n <= 0) return;
    int i, j, s;
    i = 0, j = 0, s = a[j];
    while (j < n) {
        if (s == M) {
            printf("%dth through %dth elements\n", i + 1, j + 1);
            return;
        } else if (s < M) {
            j++;
            s += a[j];
        } else {
            s -= a[i];
            i++;
        }
    }
}


来源:https://stackoverflow.com/questions/35608015/algorithm-to-find-a-consecutive-sub-sequence-whose-sum-would-be-a-asked-number-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!