- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 count number of valid triangle triplets in C++
Suppose we have an array of numbers, we have to find the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. So if the input is like [2,2,3,4], then the result will be 3 as there are three triplets [2,3,4] using first 2, [2,3,4] using second 2, and [2,2,3].
To solve this, we will follow these steps −
ret := 0, n := size of nums, sort nums
for i in range n − 1 down to 0
right := i − 1, left := 0
while left < right
sum := nums[left] + nums[right]
if sum > nums[i], then increase ret by right − left, decrease right by 1, otherwise increase left by 1
return ret
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int triangleNumber(vector<int>& nums) { int ret = 0; int n = nums.size(); sort(nums.begin(), nums.end()); for(int i = n − 1; i >= 0; i−−){ int right = i − 1; int left = 0; while(left < right){ int sum = nums[left] + nums[right]; if(sum > nums[i]){ ret += right − left; right−−; }else left++; } } return ret; } }; main(){ vector<int> v = {2,2,3,4}; Solution ob; cout << (ob.triangleNumber(v)); }
Input
[2,2,3,4]
Output
3
- Related Articles
- Valid Triangle Number in C++
- Count number of triplets with product equal to given number in C++
- Count number of triplets with product equal to given number with duplicates allowed in C++
- C++ Program to count operations to make filename valid
- Program to find number of good triplets in Python
- Count ways to form minimum product triplets in C++
- C++ program to count number of minutes needed to increase stick length to form a triangle
- Count number of triplets in an array having sum in the range [a,b] in C++
- Number of Valid Subarrays in C++
- Program to count number of isosceles triangle from colored vertex regular polygon in Python
- Program to count number of valid pairs from a list of numbers, where pair sum is odd in Python
- Count number of triplets (a, b, c) such that a^2 + b^2 = c^2 and 1
- C# program to count number of bytes in an array
- C++ code to count colors to paint elements in valid way
- C/C++ Program to Count trailing zeroes in factorial of a number?

Advertisements