Problem statement

https://leetcode.com/problems/two-sum-less-than-k/

Solution

The idea as with all 2sum problems: sort our data and do 2 pointers technique.

Complexity

Time complexity is O(n log n), space is O(n).

Code

class Solution:
    def twoSumLessThanK(self, nums, k):
        nums = sorted(nums)
        beg, end, ans = 0, len(nums) - 1, -1
        while beg < end:
            if nums[beg] + nums[end] >= k:
                end -= 1
            else: 
                ans = max(ans, nums[beg] + nums[end])
                beg += 1
                
        return ans