코딩 테스트
백준 투포인터 2230
__sapar
2024. 11. 1. 17:35
start end 를 두고 특정 기준 m 에 따라 start 혹은 end 를 ++ 하면서 풀어가면 모든 경우의 수를 확인 가능하다.
O(n) 정도로 그럭저럭....
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
#include <algorithm>
using namespace std;
int n, m;
int main(void)
{
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> n >> m;
vector<int> arr(n);
for (int i = 0; i < n; ++i)
{
cin >> arr[i];
}
sort(arr.begin(), arr.end());
int startIdx = 0;
int endIdx = 0;
int answer = INT_MAX;
while (startIdx<n)
{
int Cal = abs(arr[startIdx] - arr[endIdx]);
if (Cal < m)
{
if (endIdx < n - 1)
{
endIdx++;
}
else
{
startIdx++;
}
}
else if (Cal > m)
{
startIdx++;
if (answer > Cal)
{
answer = Cal;
}
}
else
{
answer = Cal;
break;
}
}
cout << answer;
return 0;
}