题解 | 小红的整数配对

小红的整数配对

https://www.nowcoder.com/practice/7fc314de9064479baddd77848c4c7d95

//  #牛客春招刷题训练营# https://www.nowcoder.com/discuss/726480854079250432
//  贪心:1. 相乘的数尽可能接近; 2. 优先为大的数匹配; 3. 作者不会数学证明。
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
#define all(x) x.begin(), x.end()
#define ll long long

int main() {
  ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  int n, k;
  cin >> n >> k;
  vector<int> a(n);
  for (int i = 0; i < n; i++){
    cin >> a[i];
  }
  sort(all(a));//---排序
  int index = n - 2;//--------记录选取的数中小的哪个数的索引
  ll ans = 0;
  while(index >= 0){
    if (a[index + 1] - a[index] <= k){
      ans += static_cast<ll>(a[index + 1]) * a[index];//---------10^5,用ll放溢出
      index -= 2;
    }
    else{
      index--;
    }
  }
  cout << ans;
  return 0;
}
// 64 位输出请用 printf("%lld")

#写题解领奖励##牛客春招刷题训练营#
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-07 13:15
点赞 评论 收藏
分享
06-13 10:15
门头沟学院 Java
想去夏威夷的大西瓜在...:我也是27届,但是我现在研一下了啥项目都没有呀咋办,哎,简历不知道咋写
点赞 评论 收藏
分享
好想摆:一想到我苦苦追求的迪子私下里却是985的马子,我的心就在滴血😭😭😭
点赞 评论 收藏
分享
码农索隆:单休一个月少休息4天,一年就是48天,平时节假日,别人3天假期,单休的两天
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务