如何找到符合其总和大于给定值的子数组K
?
我想出的是在序列的开始和结束处保持指针,并逐渐减去较小的指针以缩短序列。但似乎无效。为什么?
这是我的实现:
#include <iostream>
using namespace std;
int main() {
while (!cin.eof()) {
int caseCount;
cin >> caseCount;
int N, S;
for (int i = 0; i < caseCount; i++) {
cin >> N >> S;
int * seq = new int[N];
int maxSum = 0;
for (int j = 0; j < N; j ++) {
cin >> seq[j];
maxSum += seq[j];
}
if (maxSum < S) {
cout << 0 << endl;
continue;
}
int left, right;
left = 0;
right = N-1;
while(left < right) {
if(seq[left] < seq[right]) {
if (maxSum - seq[left] < S) {
cout << right-left+1 << endl;
break;
} else {
maxSum -= seq[left];
left++;
}
} else {
if (maxSum - seq[right] < S) {
cout << right-left+1 << endl;
break;
} else {
maxSum -= seq[right];
right--;
}
}
}
if (left >= right) {
cout << 1 << endl;
}
}
}
return 0;
}
样本输入:
2 // amount of sequences to input
10 15 // sequence 1 length and K
5 1 3 5 10 7 4 9 2 8 // sequence 1 data
5 11 // sequence 2 length and K
1 2 3 4 5 // sequence 2 data
样本输出:
2
3