Skip to main content
Back to problems
#1679
Medium Algorithms

Max number of k sum pairs

Array Hash Table Two Pointers Sorting
56.9% acceptance
Feb 25, 2026
3540
122
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. Return the maximum number of operations you can perform.

Solution

Rust
Time O(n log n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn max_operations(mut nums: Vec<i32>, k: i32) -> i32 {
    nums.sort_unstable();
    let mut left = 0;
    let mut right = nums.len() - 1;
    let mut ops = 0;
    while left < right {
      let sum = nums[left] + nums[right];
      match sum.cmp(&k) {
        std::cmp::Ordering::Equal => {
          ops += 1;
          left += 1;
          right -= 1;
        }
        std::cmp::Ordering::Less => left += 1,
        std::cmp::Ordering::Greater => right -= 1,
      }
    }
    ops
  }
}