We define a subarray of array a to be a contiguous block of a's elements having a length that is less than or equal to the length of array a. For example, the subarrays of array a = [1, 2, 3] are [1], [2], [1, 2], [2, 3], and [1, 2, 3]. Now, let's say we have an integer, k = 3. The subarrays of a having elements that sum to a number ≤ k are [1], [2], and [1, 2]. The longest of these subarrays is [1, 2], which has a length of 2.
Complete the maxLength function in the editor. It has 2 parameters:
- An array of integers, a.
- An integer, k.
The function must return the length of the longest subarray having elements that sum to a number less than or equal to k.
- 简单解法
static int maxLength(int[] a, int k) {
int result = -1;
for (int start = 0; start < a.length; start++) {
int sum = 0;
int cnt = 0;
int i = start;
while (i < a.length && sum + a[i] <= k) {
sum += a[i++];
cnt++;
}
result = Math.max(cnt, result);
}
return result;
}
- 优化解法
此种解法有很多的优化空间,例如在进行以第二个元素开头的尝试时,除了第一个元素外,第一次尝试的序列一定都在第二次尝试的序列内,
所以可以减去第一个元素,然后在此基础上在尾部加入新的元素;
static int maxLength(int[] a, int k) {
int result = -1;
int start = 0;
int sum = 0, cnt = 0;
int i = start;
while (i < a.length && sum + a[i] <= k) {
sum += a[i++];
cnt++;
}
result = cnt;
while (start < a.length) {
sum -= a[start++];
cnt--;
while (i < a.length && sum + a[i] <= k) {
sum += a[i++];
cnt++;
}
result = Math.max(cnt, result);
if (i >= a.length) break;
}
return result;
}