알고리즘/LeetCode
[Leetcode]Max Number of K-Sum Pairs (C++)
라이언납시오
2023. 8. 14. 10:53
728x90
반응형
Max Number of K-Sum Pairs - LeetCode
Can you solve this real interview question? Max Number of K-Sum Pairs - You are given an integer array nums and an integer k. In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. Return the maximum nu
leetcode.com
1. 주의할 점
- Map을 활용해도 좋지만, 불필요한 메모리 사용은 지양한다
2. 구현
- Nums를 오름차순으로 정렬한다
- 투 포인터를 이용하여 L은 왼쪽부터 오른쪽으로, R은 오른쪽부터 왼쪽으로 이동하여 둘이 만나기전까지 While문을 수행한다
- 둘이 가리키는 합이 K와 같다면 Answer++를 하고 다음 수로 넘어간다
- 합이 K보다 작다면 L을 늘려서 합이 커질 수 있도록 한다
- 합이 K보다 크다면 R을 줄여 합이 작아질 수 있도록 한다
class Solution {
public:
int maxOperations(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int answer = 0;
int l = 0, r = nums.size()-1;
while(l < r){
int sum = nums[l] + nums[r];
if(sum == k){
answer++;
l++;
r--;
}
else if(sum < k) l++;
else r--;
}
return answer;
}
};
728x90
반응형