NeetCode #194LC-1099EasyTwo Pointers
← Back to All Problems#194 · #1099 · Two Sum Less Than K(小于 K 的两数之和)
📌 Problem Statement & Constraints
Given an array
nums and an integer k, return the maximum nums[i] + nums[j] where i < j and the sum is less than k. If no such pair exists, return -1. Constraints: 1 <= nums.length <= 100, 1 <= nums[i] <= 1000, 0 <= k <= 2000.💡 Core Algorithmic Approaches
- Sort the array and use two pointers at the ends.
- If the sum is less than
k, record it as a candidate and move the left pointer right to try for a larger sum. - If the sum is at least
k, move the right pointer left to reduce it. - Because we want the largest sum strictly below
k, sorting is essential -- an unsorted two-pointer scan has no such monotone structure.
💻 Benchmark Python3 Implementation
class Solution:
def twoSumLessThanK(self, nums: List[int], k: int) -> int:
nums.sort()
i, j = 0, len(nums) - 1
best = -1
while i < j:
s = nums[i] + nums[j]
if s < k:
best = max(best, s) # valid candidate
i += 1 # try to get closer to k
else:
j -= 1 # too large
return best⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n log n): the sort dominates; the scan is O(n).
💾 Space Complexity
O(1) beyond the sort.
⚠️ Interview Pitfalls & Follow-ups
- Using
<= k: the sum must be strictly less thank. - Returning 0 when no pair exists: the answer must be
-1, and 0 is not achievable givennums[i] >= 1. - Skipping the sort: without sortedness, moving a pointer has no predictable effect on the sum.
- Sorting and then returning the pair's indices: this variant returns the sum, not indices.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Two Pointers Problems
中文速览与面试要点
小于 K 的两数之和
给你一个整数数组 nums 和整数 k,返回最大和 sum ,满足存在 i < j 使得 nums[i] + nums[j] = sum 且 sum < k 。如果没有满足条件的 i、j 存在,返回 −1。约束:1 ≤ nums.length ≤ 100;1 ≤ nums[i] ≤ 1000;1 ≤ k ≤ 2000。
核心要点
- 排序 + 相向双指针(标准解) :排序后,l 指向最小、r 指向最大。
- 移动策略 :若 nums[l] + nums[r] < k ,则该和是一个可行候选,更新最优值并令 l += 1 (尝试更大的和);否则和过大,令 r -= 1 。
- 为什么能取到最大值 :当和小于 k 时, nums[l] 与任何 ≤ nums[r] 的元素之和都不超过当前值,因此可以安全排除 l;当前值就是「以 l 为左端点的最优解」。
- 初值设为 −1 :表示不存在满足条件的组合,天然处理该情况。
常见陷阱
- 条件写成 s <= k :题目要求严格小于 k。
- 和小于 k 时忘记更新 best :必须在此分支更新,因为这是当前能取到的最大值。
- 和小于 k 时让 r 左移 :方向反了。和小于 k 时应增大和,即让 l 右移。
- 返回 0 而非 −1 :不存在满足条件的组合时应返回 −1(nums[i] ≥ 1,所以 0 不会是合法答案,但语义上仍应用 −1 表示无解)。
参考实现
class Solution:
def twoSumLessThanK(self, nums: list[int], k: int) -> int:
nums.sort()
l, r = 0, len(nums) - 1
best = -1
while l < r:
s = nums[l] + nums[r]
if s < k:
if s > best:
best = s
l += 1 # 和还可以更大
else:
r -= 1 # 和过大,需要更小
return best