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

 Live Demo

#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

Updated on: 04-May-2020

441 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements