- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# 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 Articles
- Python – Elements with factors count less than K
- Print triplets with sum less than or equal to k in C Program
- Find the Number of subarrays having sum less than K using C++
- Subarray Product Less Than K in C++
- Program to find sum of two numbers which are less than the target in Python
- Sum of two elements just less than n in JavaScript\n
- Count the number of words having sum of ASCII values less than and greater than k in C++
- Python – Extract dictionaries with values sum greater than K
- 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++
- Count all subsequences having product less than K in C++
- Python Program to remove elements that are less than K difference away in a list
- Maximum subarray size, such that all subarrays of that size have sum less than k in C++ program
- Count of alphabets having ASCII value less than and greater than k in C++
- How can you separate two liquids that have less than 25 K difference of boiling points?

Advertisements