You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@@ -51,6 +51,8 @@ The first case is when $$x$$ is same as $$k - x$$. In this case, we can only tak
51
51
52
52
Otherwise, we can only take the minimal value of $$m[x]$$and $$m[k - x]$$, then update the hash map values.
53
53
54
+
<Tabs>
55
+
<TabItemvalue="cpp"label="C++">
54
56
<SolutionAuthorname="@wingkwong"/>
55
57
56
58
```cpp
@@ -78,11 +80,44 @@ public:
78
80
}
79
81
};
80
82
```
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>
81
112
82
113
## Approach 2: Two Pointers
83
114
84
115
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.
0 commit comments