题解 | 小红的整数配对

小红的整数配对

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")

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

相关推荐

昨天 13:43
门头沟学院 Java
longerluck...:我猜说的是“你真**是个天才”
投递美团等公司10个岗位
点赞 评论 收藏
分享
06-23 11:28
门头沟学院 Java
牛客91966197...:也有可能是点拒绝的时候自动弹的话术
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-18 18:23
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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