#1099
Easy Algorithms Two sum less than k
Array Two Pointers Binary Search Sorting
62.1% acceptance
Mar 31, 2026
1173
135
Given an array nums of integers and integer k, return the maximum sum such that there exists i < j with nums[i] + nums[j] = sum and sum < k. If no i, j exist satisfying this equation, return -1.
Solution
Rust
Time O(n log n)
Space O(1)
impl Solution {
pub fn two_sum_less_than_k(mut nums: Vec<i32>, k: i32) -> i32 {
nums.sort_unstable();
let mut ans = -1;
let (mut lo, mut hi) = (0, nums.len() - 1);
while lo < hi {
let sum = nums[lo] + nums[hi];
if sum < k {
ans = ans.max(sum);
lo += 1;
} else {
hi -= 1;
}
}
ans
}
}