Max Number of K-Sum Pairs - LeetCode
한 연산에서 배열에서 합이 k가 되는 두 숫자를 선택하고, 해당 숫자들을 배열에서 제거할 수 있습니다.
배열에서 수행할 수 있는 최대 연산 횟수를 반환하세요.
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.
문제 요약:
주어진 배열에서 합이 k가 되는 숫자 쌍을 찾아내고, 해당 숫자 쌍을 제거할 수 있는 최대 연산 횟수를 찾는 문제입니다.
풀이과정:
주어진 배열 nums를 순회하면서 합이 k가 되는 숫자 쌍을 찾아내야 합니다. 이를 위해 다음과 같은 절차를 따릅니다:
class Solution {
public int maxOperations(int[] nums, int k) {
int removeCnt = 0;
HashMap<Integer, Integer> hM = new HashMap<>();
for(int num : nums){
hM.put(num, hM.getOrDefault(num, 0) + 1);
}
for(Integer num : hM.keySet()){
int num2 = k - num;
if(hM.containsKey(num2) && hM.get(num2) > 0 && hM.get(num) > 0){
if(num == num2){
int minCount = hM.get(num) /2;
hM.put(num, minCount);
removeCnt += minCount;
}else{
int minCount = Math.min(hM.get(num), hM.get(num2));
hM.put(num, hM.get(num) - minCount);
hM.put(num2, hM.get(num2) - minCount);
removeCnt += minCount;
}
}
}
return removeCnt;
}
}
1456. Maximum Number of Vowels in a Substring of Given Length (0) | 2023.11.02 |
---|---|
643. Maximum Average Subarray I (0) | 2023.11.02 |
11. Container With Most Water (0) | 2023.11.02 |
1431. Kids With the Greatest Number of Candies (0) | 2023.11.01 |
443. String Compression (0) | 2023.10.30 |