Two Sum Less Than K in Python

The Two Sum Less Than K problem asks us to find the maximum sum of two distinct elements in an array that is less than a given value K. If no such pair exists, we return -1.

Given an array A and integer K, we need to find the maximum sum S where S = A[i] + A[j], i

Algorithm Steps

Here's the approach to solve this problem ?

  • Initialize result as -1
  • If array has only one element, return -1 (need at least 2 elements)
  • Use nested loops to check all possible pairs
  • For each valid sum less than K, update the maximum
  • Return the maximum sum found

Method 1: Brute Force Approach

The straightforward approach checks all possible pairs and tracks the maximum sum ?

class Solution:
    def twoSumLessThanK(self, A, K):
        max_sum = -1
        
        # Need at least 2 elements
        if len(A) < 2:
            return -1
            
        # Check all pairs
        for i in range(len(A)):
            for j in range(i + 1, len(A)):
                current_sum = A[i] + A[j]
                if current_sum < K:
                    max_sum = max(max_sum, current_sum)
        
        return max_sum

# Test the solution
solution = Solution()
A = [34, 23, 1, 24, 75, 33, 54, 8]
K = 60
result = solution.twoSumLessThanK(A, K)
print(f"Array: {A}")
print(f"K: {K}")
print(f"Maximum sum less than K: {result}")
Array: [34, 23, 1, 24, 75, 33, 54, 8]
K: 60
Maximum sum less than K: 58

Method 2: Optimized Two-Pointer Approach

We can optimize using sorting and two pointers to reduce time complexity ?

class Solution:
    def twoSumLessThanK(self, A, K):
        if len(A) < 2:
            return -1
        
        A.sort()  # Sort the array
        left, right = 0, len(A) - 1
        max_sum = -1
        
        while left < right:
            current_sum = A[left] + A[right]
            
            if current_sum < K:
                max_sum = max(max_sum, current_sum)
                left += 1  # Try larger sum
            else:
                right -= 1  # Try smaller sum
        
        return max_sum

# Test the optimized solution
solution = Solution()
A = [34, 23, 1, 24, 75, 33, 54, 8]
K = 60
result = solution.twoSumLessThanK(A, K)
print(f"Array: {A}")
print(f"K: {K}")
print(f"Maximum sum less than K: {result}")
Array: [34, 23, 1, 24, 75, 33, 54, 8]
K: 60
Maximum sum less than K: 58

Example with Edge Cases

Let's test various scenarios including edge cases ?

def test_two_sum_less_than_k():
    solution = Solution()
    
    # Test cases
    test_cases = [
        ([34, 23, 1, 24, 75, 33, 54, 8], 60, 58),  # Normal case
        ([10, 20, 30], 15, -1),  # No valid pairs
        ([1, 2, 3, 4], 6, 5),    # Multiple valid pairs
        ([5], 10, -1),           # Single element
        ([1, 1, 1], 3, 2)        # Duplicate elements
    ]
    
    for i, (arr, k, expected) in enumerate(test_cases):
        result = solution.twoSumLessThanK(arr.copy(), k)
        status = "?" if result == expected else "?"
        print(f"Test {i+1} {status}: Array={arr}, K={k}, Result={result}, Expected={expected}")

test_two_sum_less_than_k()
Test 1 ?: Array=[34, 23, 1, 24, 75, 33, 54, 8], K=60, Result=58, Expected=58
Test 2 ?: Array=[10, 20, 30], K=15, Result=-1, Expected=-1
Test 3 ?: Array=[1, 2, 3, 4], K=6, Result=5, Expected=5
Test 4 ?: Array=[5], K=10, Result=-1, Expected=-1
Test 5 ?: Array=[1, 1, 1], K=3, Result=2, Expected=2

Complexity Analysis

Method Time Complexity Space Complexity Best For
Brute Force O(n²) O(1) Small arrays, preserves original order
Two Pointers O(n log n) O(1) Large arrays, better average performance

Conclusion

The Two Sum Less Than K problem can be solved using brute force O(n²) or optimized two-pointer approach O(n log n). The brute force method is simpler to understand, while the two-pointer method is more efficient for larger datasets.

Updated on: 2026-03-25T08:07:58+05:30

928 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements