jayati

Count the number of possible triangle

Sep 29th, 2023
1,083
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5.  
  6. // } Driver Code Ends
  7. class Solution
  8. {
  9.     public:
  10.     //Function to count the number of possible triangles.
  11.     int findNumberOfTriangles(int arr[], int n)
  12.     {
  13.        
  14.    
  15.  
  16.     sort(arr, arr+n);
  17.  
  18.     int count = 0;
  19.  
  20.     for (int i = n - 1; i >= 1; i--) {
  21.         int l = 0, r = i - 1;
  22.         while (l < r) {
  23.             if (arr[l] + arr[r] > arr[i]) {
  24.  
  25.                 // If it is possible with a[l], a[r]
  26.                 // and a[i] then it is also possible
  27.                 // with a[l+1]..a[r-1], a[r] and a[i]
  28.                 count += r - l;
  29.  
  30.                 // checking for more possible solutions
  31.                 r--;
  32.             }
  33.             else
  34.  
  35.                 // if not possible check for
  36.                 // higher values of arr[l]
  37.                 l++;
  38.         }
  39.     }
  40.     return count;
  41.     }
  42. };
  43.  
  44.  
  45. //{ Driver Code Starts.
  46.  
  47. int main()
  48. {
  49.     int T;
  50.     cin>>T;
  51.     while(T--)
  52.     {
  53.         int n;
  54.         cin>>n;
  55.         int arr[n];
  56.         for(int i=0; i<n; i++)
  57.             cin>>arr[i];
  58.         Solution ob;
  59.         cout<<ob.findNumberOfTriangles(arr,n) <<endl;
  60.     }
  61.     return 0;
  62. }
  63. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment