Two Sum Less Than K in Python

PythonServer Side ProgrammingProgramming

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
  • return res


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

 Live Demo

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()




Updated on 28-Apr-2020 08:31:32