2 条题解

  • 0
    @ 2026-3-12 13:31:50
    import sys
    input = lambda:sys.stdin.readline().strip()
    
    n,k=map(int,input().split())
    a=sorted(list(map(int,input().split())))
    res=0
    for j in range(len(a)-1,-1,-1):
        ans=a[j]
        for i in range(0,j):
            if a[j] - a[i] <= k:ans+=a[i]
        res=max(res,ans)
    print(res)
    
    • 0
      @ 2026-3-10 17:22:55

      由题意,选宝箱的顺序无所谓,又和最大值最小值相关,所以我们可以先给数组排个序,然后初始化两个指针l和r,枚举r,当a[r]-a[l]>k时,l++, 完了。

      #include<bits/stdc++.h>
      using namespace std;
      #define int long long
      int n,k,ans,tot;
      int a[101000],s[101000];
      signed main(){
          cin>>n>>k;
          for(int i=1;i<=n;i++){
              cin>>a[i];
          }
          sort(a+1,a+1+n);
          int l=1;
          for(int r=1;r<=n;r++){
              tot+=a[r];//右指针入队
              while(a[r]-a[l]>k){//不满足条件左指针出队
                  tot-=a[l];
                  l++;
              }
              ans=max(ans,tot);//用前缀和也行
          }
          cout<<ans;
      }
      
      • 1

      信息

      ID
      168
      时间
      1000ms
      内存
      256MiB
      难度
      2
      标签
      递交数
      86
      已通过
      37
      上传者