1.数组全是正数
思路:
用两个指针,左,右 指针初始都指向数组0位置。记录左、右区间和。
- 如大于k则左指针+1。
- 如果小于K则右指针+1
- 如果等于k则左右指针同时+1
#include <iostream> using namespace std; int maxSubKSequence(int *a, int k, int length) { int i = 0, j = 0, res = 0, max = 0; while (j < length) { if (res < k) { res += a[j++]; } else if (res > k) { res -= a[i++]; } else { max = max > j - i + 1 ? max : j - i + 1; res += a[j++]; res -= a[i++]; } } return max; } int main() { int a[10] = { 1,4,5,3,1,0,5,4,4,6}; cout << maxSubKSequence(a, 13, 10); return 0; }