Program to find number of unique four indices where they can generate sum less than target from four lists in python

PythonServer Side ProgrammingProgramming

Suppose we have four list of numbers A, B, C and D and also have another number target. We have to find the number of different unique indices i, j, k, l such that A[i] + B[j] + C[k] + D[l] ≤ target.

So, if the input is like A = [3, 2] B = [5, 3] C = [1] D = [2, 3] target = 9, then the output will be 3, as We can pick the following combinations: [3, 3, 1, 2] [3, 3, 1, 2] [2, 3, 1, 3]

To solve this, we will follow these steps:

  • temp_list := a new list
  • for i in range 0 to size of A, do
    • for j in range 0 to size of B, do
      • insert (A[i] + B[j]) at the end of temp_list
  • sort the list temp_list
  • ans := 0
  • for i in range 0 to size of C, do
    • for j in range 0 to size of D, do
      • sum_cd := C[i] + D[j]
      • sum_ab := target - sum_cd
      • ans := ans + number of elements in temp_list whose sum <= sum_ab
  • return ans

Let us see the following implementation to get better understanding:

Example

Live Demo

from bisect import bisect_right

class Solution:
   def solve(self, A, B, C, D, target):
      temp_list = []
      for i in range(len(A)):
         for j in range(len(B)):
            temp_list.append(A[i] + B[j])

      temp_list.sort()

      ans = 0
      for i in range(len(C)):
         for j in range(len(D)):
            sum_cd = C[i] + D[j]
            sum_ab = target - sum_cd

            ans += bisect_right(temp_list, sum_ab)

      return ans

ob = Solution()
A = [3, 2]
B = [5, 3]
C = [1]
D = [2, 3]
target = 9
print(ob.solve(A, B, C, D, target))

Input

[3, 2], [5, 3], [1], [2, 3], 9

Output

3
raja
Published on 26-Nov-2020 07:42:59
Advertisements