![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find number of unique four indices where they can generate sum less than target from four lists in python
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
- for j in range 0 to size of B, do
- 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
- for j in range 0 to size of D, do
- return ans
Let us see the following implementation to get better understanding:
Example
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
Advertisements