简体   繁体   中英

Maximum contiguous sub-array (With most number of elements)

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?

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.

它似乎是最大子数组问题的上限版本: http : //en.wikipedia.org/wiki/Maximum_subarray_problem我想您可以从现有算法中找到灵感。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM