![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 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
Advertisements