问题描述:
给定一个无序数组arr,其中元素可正、可负、可0,给定一个整数 k。求arr所有的子数组中累加和小于或等于k的最长子数组长度。例如:arr=[3,-2,-4,0,6],k=-2,相加和小于或等于-2的最长子数组为{3,-2,-4,0},所以结果返回4。
代码如下:
int getLessIndex(int arr[], int len, int num) { int low = 0; int high = len - 1; int mid = 0; int ret = -1; while(low <= high) { mid = (low + high) / 2; if(arr[mid] >= num) { ret = mid; high = mid - 1; } else { low = mid + 1; } } return ret; } int maxLength(int arr[], int len, int k) { int *pSums = new int[len + 1]; int sum = 0; pSums[0] = sum; for(int i = 0; i < len; ++i) { sum += arr[i]; pSums[i + 1] = max(sum, pSums[i]); } sum = 0; int ret = 0; int idx = 0; int dis = 0; for(int i = 0; i < len; ++i) { sum += arr[i]; idx = getLessIndex(pSums, len, sum - k); dis = (idx == -1 ? 0 : i - idx + 1); ret = max(ret, dis); } delete[] pSums; return ret; }