[LeetCode] Two Sum Less Than K

1099. Two Sum Less Than K

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int twoSumLessThanK(vector<int>& nums, int k) {
int res = -1;
sort(begin(nums), end(nums));
int l = 0, r = nums.size() - 1;
while(l < r) {
if(nums[l] + nums[r] < k) res = max(res, nums[l++] + nums[r]);
else r--;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/01/PS/LeetCode/two-sum-less-than-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.