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`.

Example 1:

```Input: nums = [34,23,1,24,75,33,54,8], k = 60
Output: 58
Explanation: We can use 34 and 24 to sum 58 which is less than 60.
```

Example 2:

```Input: nums = [10,20,30], k = 15
Output: -1
Explanation: In this case it is not possible to get a pair sum less that 15.
```

Constraints:

• `1 <= nums.length <= 100`
• `1 <= nums[i] <= 1000`
• `1 <= k <= 2000`

1099. Two Sum Less Than K
``````struct Solution;

impl Solution {
fn two_sum_less_than_k(mut a: Vec<i32>, k: i32) -> i32 {
a.sort_unstable();
let n = a.len();
let mut l = 0;
let mut r = n - 1;
let mut res = -1;
while l < r {
let sum = a[l] + a[r];
if sum < k {
res = res.max(sum);
l += 1;
} else {
r -= 1;
}
}
res
}
}

#[test]
fn test() {
let a = vec![34, 23, 1, 24, 75, 33, 54, 8];
let k = 60;
let res = 58;
assert_eq!(Solution::two_sum_less_than_k(a, k), res);
let a = vec![10, 20, 30];
let k = 15;
let res = -1;
assert_eq!(Solution::two_sum_less_than_k(a, k), res);
}
``````