4

Given an array of natural numbers and an another natural T, how to find the contiguous subarray with sum less than or equal to T but the number of element in this subarray is maximized?

For example, if the given array is:

{3, 1, 2, 1, 1} and T = 5. Then the maximum contigous subarray is {1, 2, 1, 1} because it will contain 5 elements and the sum is equal to 5.

Another example: {10,1,1,1,1,3,6,7} with T = 8. Then the maximum contigous subarray is ${1,1,1,1,3}$

I can do it with O(n^2) operation. However I am looking for a linear time solution for this problem. Any ideas?

1
  • To me it seems a version of the Knapsack Problem. Commented Mar 4, 2013 at 18:59

2 Answers 2

2

It ought to be possible to do this with O(n). I've not tested this, but it looks OK:

int start = 0, end = 0;
int beststart = 0, bestend = 0;
int sum = array[0];

while (end + 1 < arraysize) {
  if (array[end + 1] + sum <= T)
    sum += array[end++];
  else
    sum -= array[start++];
  if ((end - start) > (bestend - beststart)) {
    beststart = start;
    bestend = end;
  }
}

So, basically, it moves a sliding window along the array and records the point at which end - start is the greatest.

Sign up to request clarification or add additional context in comments.

2 Comments

I think you need another check ` if ((end - start) > (bestend - beststart)) { beststart = start; bestend = end; }` at the end.
@Quixotic: is that better now?
0

It seems to be a capped version of the Maximum subarray problem: http://en.wikipedia.org/wiki/Maximum_subarray_problem I guess you can find inspirations with existing algorithms.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.