Skip to content

Commit 6d941d3

Browse files
authored
solutions: 1679 - Max Number of K-Sum Pairs (#679)
1 parent d82db05 commit 6d941d3

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

solutions/1600-1699/1679-max-number-of-k-sum-pairs-medium.md

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
---
2-
description: 'Author: @wingkwong | https://leetcode.com/problems/max-number-of-k-sum-pairs/'
2+
description: 'Author: @wingkwong, @vigneshshiv | https://leetcode.com/problems/max-number-of-k-sum-pairs/'
33
---
44

55
# 1679 - Max Number of K-Sum Pairs (Medium)
@@ -51,6 +51,8 @@ The first case is when $$x$$ is same as $$k - x$$. In this case, we can only tak
5151

5252
Otherwise, we can only take the minimal value of $$m[x]$$and $$m[k - x]$$, then update the hash map values.
5353

54+
<Tabs>
55+
<TabItem value="cpp" label="C++">
5456
<SolutionAuthor name="@wingkwong"/>
5557

5658
```cpp
@@ -78,11 +80,44 @@ public:
7880
}
7981
};
8082
```
83+
</TabItem>
84+
85+
<TabItem value="java" label="Java">
86+
<SolutionAuthor name="@vigneshshiv"/>
87+
88+
```java
89+
class Solution {
90+
public int maxOperations(int[] nums, int k) {
91+
int count = 0;
92+
Map<Integer, Integer> table = new HashMap<>();
93+
for (int x : nums) {
94+
int reminder = k - x;
95+
if (table.containsKey(reminder)) {
96+
count += 1;
97+
if (table.get(reminder) == 1) {
98+
table.remove(reminder);
99+
} else {
100+
table.merge(reminder, -1, Integer::sum);
101+
}
102+
} else {
103+
table.merge(x, 1, Integer::sum);
104+
}
105+
}
106+
return count;
107+
}
108+
}
109+
```
110+
</TabItem>
111+
</Tabs>
81112

82113
## Approach 2: Two Pointers
83114

84115
We can sort the input and use two pointers to track elements from both side. If their sum is equal to $$k$$, then we increase $$ans$$ by 1. If $$nums[i] + nums[j] > k$$, it means we should reduce the sum, hence we move $$j$$-th pointer to the left . Otherwise, we increase $$i$$-th pointer to the right to increase the sum.
85116

117+
<Tabs>
118+
<TabItem value="cpp" label="C++">
119+
<SolutionAuthor name="@wingkwong"/>
120+
86121
```cpp
87122
class Solution {
88123
public:
@@ -98,3 +133,6 @@ public:
98133
}
99134
};
100135
```
136+
137+
</TabItem>
138+
</Tabs>

0 commit comments

Comments
 (0)