
- 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
Program to check number of triplets from an array whose sum is less than target or not Python
Suppose we have a list of numbers called nums and another value target, we have to find the number of triples (i < j < k) that exist such that nums[i] + nums[j] + nums[k] < target.
So, if the input is like nums = [−2, 6, 4, 3, 8], target = 12, then the output will be 5, as the triplets are: [−2,6,4], [−2,6,3], [−2,4,3], [−2,4,8], [−2,3,8]
To solve this, we will follow these steps −
sort the list nums
ans := 0
n := size of nums
for i in range 0 to n−1, do
k := n − 1
for j in range i + 1 to n−1, do
while k > j and nums[i] + nums[k] + nums[j] >= target, do
k := k − 1
if j is same as k, then
ans := ans + k − j
return ans
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums, target): nums.sort() ans = 0 n = len(nums) for i in range(n): k = n − 1 for j in range(i + 1, n): while k > j and nums[i] + nums[k] + nums[j] >= target: k -= 1 if j == k: break ans += k − j return ans ob1 = Solution() nums = [−2, 6, 4, 3, 8] target = 12 print(ob1.solve(nums, target))
Input
[-2, 6, 4, 3, 8], 12
Output
5
- Related Articles
- Print triplets with sum less than or equal to k in C Program
- Program to find number of sublists whose sum is given target in python
- Program to find number of unique four indices where they can generate sum less than target from four lists in python
- Program to find sum of two numbers which are less than the target in Python
- Get the Triplets in an Array Whose Sum is Equal to a Specific Number in Java
- Program to check robot can reach target position or not in Python
- Program to check we can get a digit pair and any number of digit triplets or not in Python
- Program to count maximum number of distinct pairs whose differences are larger than target in Python
- Program to check if the given list has Pythagorean Triplets or not in Python
- Program to check we can find four elements whose sum is same as k or not in Python
- Program to check a number is ugly number or not in Python
- C Program to check if an Array is Palindrome or not
- Swift Program to check if an Array is Palindrome or not
- Python program to check if a number is Prime or not
- Python program to check credit card number is valid or not

Advertisements