
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Valid Triangle Number in C++
Suppose we have an array consists of non-negative integers, our task is to count 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 [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
- Program to count number of valid triangle triplets in C++
- Valid triangle edges - JavaScript
- Valid Number in Python
- Number of Valid Subarrays in C++
- Number of Valid Words for Each Puzzle in C++
- Check whether triangle is valid or not if sides are given in Python
- Check whether right angled triangle is valid or not for large sides in Python
- Check if a given string is a valid number in Python
- Check if a given string is a valid number in C++
- How To Check if a Triangle is Valid or Not When Sides are Given in Java?
- Checking if a number is a valid power of 4 in JavaScript
- Program to check valid mobile number using Java regular expressions
- Minimum number of Parentheses to be added to make it valid in C++
- Valid Sudoku in Python
- Valid Parentheses in C++

Advertisements