> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Two Sum Less Than K Python Solution with Tests

> Tested Python solution for LeetCode 1099 with 12 pytest cases. Generate a practice environment with lcpy.

LeetCode 1099, [Easy](/catalog/easy). Topics: [Array](/catalog/topics/array), [Two Pointers](/catalog/topics/two-pointers), [Binary Search](/catalog/topics/binary-search), [Sorting](/catalog/topics/sorting). [View on LeetCode](https://leetcode.com/problems/two-sum-less-than-k/description/).

Generate this problem as a practice environment: tested reference solution, 12 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 1099   # by problem number
lcpy gen -s two_sum_less_than_k   # by problem name
```

## Problem

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

### Examples

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

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

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/two_sum_less_than_k/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/two_sum_less_than_k/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from bisect import bisect_left


class Solution:
    # Time: O(n log n)
    # Space: O(1)
    def two_sum_less_than_k(self, nums: list[int], k: int) -> int:
        nums.sort()
        ans = -1
        for i, x in enumerate(nums):
            j = bisect_left(nums, k - x, lo=i + 1) - 1
            if i < j:
                ans = max(ans, x + nums[j])
        return ans
```

## Complexity

| Time | Space |
| - | - |
| O(n log n) | O(1) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.