- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Two Sum Less Than K in Python

Suppose we have an array A of integers and another integer K is given. We have to find the maximum S such that there exists i < j with A[i] + A[j] = S and S < K. If there is no i, j exists satisfying this equation, then return -1. So for example if A = [34,23,1,24,75,33,54,8] and K = 60, then the output will be 58, as we can use 34 and 24 to sum 58, which is less than 60.

To solve this, we will follow these steps −

- res = - 1
- if A has only one element, then return -1
- for i in range 0 to length of A
- for j in range i + 1 to length of A
- temp = A[i] + A[j]
- if temp < K, then res = max of res and temp

- for j in range i + 1 to length of A
- return res

## Example(Python)

Let us see the following implementation to get a better understanding −

class Solution(object): def twoSumLessThanK(self, A, K): ans = -1 if len(A)==1: return -1 for i in range(len(A)): for j in range(i+1,len(A)): temp = A[i]+ A[j] if temp<K: ans = max(ans,temp) return ans ob1 = Solution() print(ob1.twoSumLessThanK([34,23,1,24,75,33,54,8],60))

## Input

[34,23,1,24,75,33,54,8] 60

## Output

58

- Related Questions & Answers
- Sum of two elements just less than n in JavaScript
- Subarray Product Less Than K in C++
- Python – Elements with factors count less than K
- Find the Number of subarrays having sum less than K using C++
- Print triplets with sum less than or equal to k in C Program
- Program to find sum of two numbers which are less than the target in Python
- Count the number of words having sum of ASCII values less than and greater than k in C++
- Count all subsequences having product less than K in C++
- Count of alphabets having ASCII value less than and greater than k in C++
- Python – Extract dictionaries with values sum greater than K
- Maximum subarray size, such that all subarrays of that size have sum less than k in C++
- Largest number less than N with digit sum greater than the digit sum of N in C++
- Python Program to remove elements that are less than K difference away in a list
- Program to count non-empty subsets where sum of min and max element of set is less than k in Python
- Maximum subarray size, such that all subarrays of that size have sum less than k in C++ program

Advertisements