- 오름차순으로 정렬.
- 왼쪽 커서와, 오른쪽 커서를 만들고,
두 커서 값의 차이에 따라, 커서의 위치를 변경. - 왼쪽 커서를 증가시키면, 차이는 감소하고,
오른쪽 커서를 증가시키면, 차이는 증가한다. - 두 커서의 값의 차이를 구할때 마다, 최솟값 갱신.
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
using int32 = int32_t;
using int64 = int64_t;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int32 N, M, min_diff = 2'000'000'001;
cin >> N >> M;
int32 A[N];
for(int32 i=0; i<N; i++) cin >> A[i];
sort(A, A+N);
int32 l = 0;
int32 r = 0;
int32 diff = 0;
while(r != N){
diff = A[r] - A[l];
if(M <= diff){
l++;
if(diff < min_diff) min_diff = diff;
}
else r++;
}
cout << min_diff;
}
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
using int32 = int32_t;
using int64 = int64_t;
const int BUF_SIZE = 1 << 20; // 메모리 초과 가능, 적당히 조절할 것.
char input_buf[BUF_SIZE], output_buf[BUF_SIZE];
int input_buf_pos, output_buf_pos;
enum io_mode {READ, WRITE};
inline void char_io(io_mode mode, char &target)
{
if(mode == READ) {
if (input_buf_pos == BUF_SIZE)
{
fread(input_buf, sizeof(char), BUF_SIZE, stdin);
input_buf_pos = 0;
}
target = input_buf[input_buf_pos++];
}
else {
if(output_buf_pos == BUF_SIZE || target == EOF)
{
fwrite(output_buf, sizeof(char), output_buf_pos, stdout);
output_buf_pos = 0;
}
output_buf[output_buf_pos++] = target;
}
}
inline void char_io(io_mode mode, char &&target){
char_io(mode, target);
}
inline void int_io(io_mode mode, int &target)
{
char c;
if(mode == READ){
bool negative = false;
int ret = 0;
while(true)
{
char_io(READ, c);
if(c == '\n' || c == ' ') break;
if(c == '-') {
negative = true;
continue;
}
ret = ret * 10 + (c & 0b1111);
}
target = negative ? -ret : ret;
}
else {
int abs = target;
int div = 1'000'000'000;
char quotient = 0;
if(abs < 0) {
char_io(WRITE, '-');
abs *= -1;
}
while(abs < div && div != 1) { div /= 10; }
while(div != 0){
quotient = '0' + (char)((abs / div)%10);
char_io(WRITE, quotient);
div /= 10;
}
}
}
inline void int_io(io_mode mode, int &&target){
int_io(mode, target);
}
int main() {
int32 N, M, min_diff = 2'000'000'001;
int_io(READ, N);
int_io(READ, M);
int32 A[N];
for(int32 i=0; i<N; i++) int_io(READ, A[i]);
sort(A, A+N);
int32 l = 0;
int32 r = 0;
int32 diff = 0;
while(r != N){
diff = A[r] - A[l];
if(M <= diff){
l++;
if(diff < min_diff) min_diff = diff;
}
else r++;
}
int_io(WRITE, min_diff);
char_io(WRITE, EOF);
}