public static int maxPoint(int[] arr,int L){ if(arr == null || arr.length == 0) return 0; int res = 1; for(int i=0; i<arr.length; i++){ int leftIndex = getLeft(arr,arr[i]-L,i); res = Math.max(res,i-leftIndex+1); } return res; } public static int getLeft(int[] arr,int value,int right){ int left = 0; int mid = left + (right-left)>>1; int index = right; while(left<=right){ if(arr[mid]>=value){ index = mid; right = mid-1; }else{ left = mid+1; } mid = left + (right-left)>>1; } return index; }
int cover(vector<int> arr,int len) { int begin = 0; int end = 0; int res = 0; while (begin< arr.size()) { while (end + 1< arr.size() && arr[end +1] <= arr[begin] + len) { ++end; } res = max(res,end - begin + 1); ++begin; } return res; }
int getMax(int length,vector<int> a) { int max=0; deque<int> dq; for(int i=0;i<a.size();++i) { while(!dq.empty() && a[i]-a[dq.front()]>length) dq.pop_front(); dq.push_back(i); max=max>dq.size()?max:dq.size(); } return max; }
package java_example;
/**
* 数轴上从左到右有 n 个点 a[0],a[1],„„,a[n-1],给定一根长度为 L 的绳子,求绳子最多能 覆盖其中的几个点。
* @author lulinlin
*
*/
public class MaxPoint {
//方法一
public static int maxPoint(int[]a,int l){
int maxCount=0;
for(int i=0;i<a.length-1;i++){
int count=1;
int j=i+1;
while((j<a.length)&&(a[j]-a[i]<=l)){
j++;
count++;
if(count>maxCount){
maxCount=count;
}
}
}
return maxCount;
}
//方法二
public static int maxPoint1(int[]a,int l){
int maxCount=0;
int begin =0;
int end=1;
while(end<a.length){
if(a[end]-a[begin]>l){
begin++;
}
else{
if(end-begin>maxCount){
maxCount=end-begin+1;
}
end++;
}
}
return maxCount;
}
public static void main(String[] args) {
int[]a= new int[]{1,3,4,6};
int l=5;
//System.out.println(maxPoint(a,l));
System.out.println(maxPoint1(a,l));
}
}
// 求最大覆盖点 #includeint maxCover(int a[], int n, int L) { int count = 2, maxCount = 1, start; int i = 0, j = 1; while(i < n && j < n) { while((j < n) && (a[j] - a[i] <= L)) { j++; count++; } // 退回到满足条件的j j--; count--; if(maxCount < count) { start = i; maxCount = count; } i++; j++; } printf("covered point: "); for(i = start; i < start + maxCount; i++) { printf("%d ", a[i]); } printf("\n"); return maxCount; } int main() { // test int a[] = {1, 3, 7, 8, 10, 11, 12, 13, 15, 16, 17, 18, 21}; printf("max count: %d\n\n", maxCover(a, 13, 8)); int b[] = {1,2,3,4,5,100,1000}; printf("max count: %d\n", maxCover(b, 7, 8)); return 0; }
有两点需要注意: