백준/2230/투 포인터/수 고르기
차이가 N이상인 길이가 2인 수열 중에 그 차이가 가장 작은 값을 찾으면 되는 문제입니다.
문제 해결을 위해 투 포인터 알고리즘을 사용하였습니다.
sort(arr, arr + N); int st = 0; int en = 1; int min_value = 0x3f3f3f3f; while(st<N) { if (arr[en] - arr[st] >= M) { if (min_value > arr[en] - arr[st]) { min_value = arr[en] - arr[st]; } st++; } else { en++; } }
우선 주어진 수열들을 정렬하고, 시작 인덱스는 0 두번째 인덱스는 1로 시작합니다.
상술한 인덱스끼리의 차이가 N보다 작을 경우에는 두번째 인덱스를 늘려 차이를 늘리고
N보다 같거나 작을 경우 시작 인덱스를 늘려 다시 그 차이를 줄이는 식으로 차이의 값을 구했습니다.
#include<iostream>
#include<algorithm>
using namespace std;
int arr[100'000];
int main()
{
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int N, M = 0;
cin >> N >> M;
for (int i = 0;i < N;i++)
{
cin >> arr[i];
}
sort(arr, arr + N);
int st = 0;
int en = 1;
int min_value = 0x3f3f3f3f;
while(st<N)
{
if (arr[en] - arr[st] >= M)
{
if (min_value > arr[en] - arr[st])
{
min_value = arr[en] - arr[st];
}
st++;
}
else
{
en++;
}
}
cout << min_value;
return 0;
}