Skip to content

Commit 2789cb1

Browse files
leetcode 1679
1 parent 8d62984 commit 2789cb1

2 files changed

Lines changed: 58 additions & 0 deletions

File tree

Leetcode/Leetcode_1679.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
from typing import List
2+
3+
class Solution:
4+
def maxOperations(self, nums: List[int], k: int) -> int:
5+
"""
6+
Problem:
7+
Find the maximum number of pairs in the array such that
8+
the sum of each pair equals k. Each element can be used only once.
9+
10+
Approach (Two Pointer Technique):
11+
1. First sort the array so that we can use two pointers.
12+
2. Use two pointers:
13+
- l (left) starting from the beginning.
14+
- r (right) starting from the end.
15+
3. Check the sum of elements at these pointers.
16+
4. If sum == k → we found a valid pair:
17+
- increase pair count
18+
- move both pointers inward
19+
5. If sum < k → move the left pointer right to increase the sum.
20+
6. If sum > k → move the right pointer left to decrease the sum.
21+
7. Continue until the pointers meet.
22+
23+
Why this works:
24+
Sorting allows us to efficiently adjust the sum by moving pointers
25+
instead of checking all possible pairs (which would be O(n²)).
26+
27+
Time Complexity (TC):
28+
Sorting takes O(n log n)
29+
Two-pointer traversal takes O(n)
30+
Overall TC = O(n log n)
31+
32+
Space Complexity (SC):
33+
O(1) → No extra data structures used (in-place operations)
34+
"""
35+
36+
pairs = 0 # Count of valid pairs
37+
nums.sort() # Sort the array to apply two-pointer technique
38+
39+
l = 0 # Left pointer
40+
r = len(nums) - 1 # Right pointer
41+
42+
# Continue until the two pointers meet
43+
while l < r:
44+
45+
n = nums[l] + nums[r] # Current pair sum
46+
47+
if k == n: # If the pair sum equals k
48+
pairs += 1 # Found a valid pair
49+
l += 1 # Move left pointer forward
50+
r -= 1 # Move right pointer backward
51+
52+
elif n < k: # If sum is smaller than k
53+
l += 1 # Increase sum by moving left pointer
54+
55+
else: # If sum is greater than k
56+
r -= 1 # Decrease sum by moving right pointer
57+
58+
return pairs # Return total number of valid pairs

practice.py

Whitespace-only changes.

0 commit comments

Comments
 (0)