给定一个有序数组arr,代表数轴上从左到右有n个点arr[0]、arr[1]...arr[n-1]。给定一个正数L,代表一根长度为L的绳子,求绳子最多能覆盖其中的几个点。
思路1. 以数组中第一个点为绳子的开头,往后一个一个遍历,看能够覆盖多少个点。以第二个点为开头,往后依次遍历,记录覆盖的点的个数,依次遍历,寻找最大值。
2. 采用二分思想,当数组中每个点都为绳子的结尾,绳子长度为L时,寻找开头的位置。如arr[3]=9,L=9,寻找>=arr[3]-L 的最左边的点的位置。
3. 以A为开头,最后一个不超过L的位置为结尾B,以第一个点为A,找满足条件的最远的B的位置,然后将A往前移动一个位置,B从当前位置继续往下遍历,寻找满足的结尾。
Java代码import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static int maxPoint(int[] arr, int L) {
int left = 0;
int right = 0;
int N = arr.length;
int max = 0;
while (left < N) {
while (right < N && arr[right] - arr[left] < L) {
right++;
}
max = Math.max(max, right - (left++));
}
return max;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int l = sc.nextInt();
int [] arr = new int [n];
for(int i = 0 ; i < n ; i++){
arr[i] = sc.nextInt();
}
System.out.println(maxPoint(arr, l));
}
}
C++代码
#includeusing namespace std; typedef unsigned long long ull; int main() { int n; int k; cin>>n>>k; int w[100010]; for(int i = 0; i < n; i++) cin>>w[i]; int l = 0; int m = 0; for(int i=0; i =k) { l++; } m = max(m,i-l+1); } cout< Python代码 n,k= input().split() n=int(n) k=int(k) N=input().split() ln=len(N) l=0 m=0 for i in range(0,ln): while int(N[i])-int(N[l])>=k: l+=1 m=max(m,i-l+1) print(m)



