Min-Max问题

本文介绍了一种算法,该算法旨在从给定的整数列表中选择K个整数,使得这些整数之间的最大值与最小值之差(不公平性)最小。通过先排序再滑动窗口的方式找到最优解,并最终输出此最小不公平性值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem Statement

Given a list of N integers, your task is to select K integers from the list such that its unfairness is minimized.

if (x1,x2,x3,…,xk) are K numbers selected from the list N, the unfairness is defined as

max(x1,x2,…,xk)−min(x1,x2,…,xk)
where max denotes the largest integer among the elements of K, and min denotes the smallest integer among the elements of K.

答案

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <climits>
using namespace std;

int main() {
    int N, K, unfairness = INT_MAX;
    cin >> N >> K;
    int list[N];
    for (int i=0; i<N; i++)
        cin >> list[i];
    vector<int> dat(list,list+sizeof(list)/sizeof(list[0]));
    sort(dat.begin(),dat.end());
    int j=K-1;
    int ret=numeric_limits<int>::max();
    while(j<N){
        ret=min(ret,dat[j]-dat[j-K+1]);
        j++;
    }
    //cout<<ret<<endl;
    /** Write the solution code here. Compute the result, store in  the variable unfairness --
    and output it**/
    unfairness=ret;
    cout << unfairness << "\n";
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值