[LeetCode | Javascript] 1679. Max Number of K-Sum Pairs

임홍원·2024년 3월 6일
post-thumbnail

LeetCode | 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 number of operations you can perform on the array.


📚입출력 예시📚

Example 1:

Input: nums = [1,2,3,4], k = 5
Output: 2
Explanation: Starting with nums = [1,2,3,4]:
- Remove numbers 1 and 4, then nums = [2,3]
- Remove numbers 2 and 3, then nums = []
There are no more pairs that sum up to 5, hence a total of 2 operations.

Example 2:

Input: nums = [3,1,3,4,3], k = 6
Output: 1
Explanation: Starting with nums = [3,1,3,4,3]:
- Remove the first two 3's, then nums = [1,4,3]
There are no more pairs that sum up to 6, hence a total of 1 operation.

💯성공한 풀이💯

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var maxOperations = function(nums, k) {
    let left = 0;
    let right = nums.length - 1;
    let count = 0;
    
    nums.sort((a, b) => a - b);
    
    while(left < right) {
        if(nums[left] + nums[right] < k) {
            left += 1;
        }else if(nums[left] + nums[right] > k) {
            right -= 1;
        }else {
            left += 1;
            right -= 1;
            count += 1;
        }
    }
    
    return count;
};

💡문제 접근 방식💡

투 포인터를 이용해서 해결하였다.
투 포인터는 한쪽을 고정해놓고 다른쪽을 움직이는 접근방식이 필요하다.

이 문제에서는 기준점을 세가지로 나누었다.
1. 왼쪽값과 오른쪽값을 더한값이 k 보다 작을때 -> 왼쪽 포인터 움직임
2. 왼쪽값과 오른쪽값을 더한값이 k 보다 클때 -> 오른쪽 포인터 움직임
3. 왼쪽값과 오른쪽값을 더한값이 k 와 같을때 -> count + 1

profile
Frontend Developer

0개의 댓글