Possible to form a triangle from array values in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array of integers. Our task is to check if the creation of a non-degenerate triangle taking the elements of the array as sides of the triangle.

Non-degenerate triangle − it is a triangle that has a positive area. The condition for a non-degenerate triangle with sides a, b, c is −

a + b > c
a + c > b
b + c > a

Let’s take an example to understand the problem better −

Input − arr[2, 5 ,9, 4, 3]

Output − Yes

Explanation − the triangle formed is 2 3 4.

To solve this problem, we will check that the above condition is satisfied by the values of the array.

A navie solution will involve direct checking of every triplet of the array.

A more effective solution will involve sorting the array elements and the checking three consecutive triplets of the array. As for sorted array if the sum of two elements is not greater than the next one check values after that is not worthy (they are already large).


Program to show the implementation of our solution

 Live Demo

#include <bits/stdc++.h>
using namespace std;
bool isTrianglePossible(int arr[], int N){
   if (N < 3)
      return false;
   sort(arr, arr + N);
   for (int i = 0; i < N - 2; i++)
      if (arr[i] + arr[i + 1] > arr[i + 2])
         return true;
int main() {
   int arr[] = {5, 12, 13, 65, 6, 1};
   int N = sizeof(arr) / sizeof(int);
   cout<<"Creation of triangle from elements of array ";
   isTrianglePossible(arr, N)?cout<<"is Possible": cout<<"is not Possible";
   return 0;


Creation of triangle from elements of array is Possible
Published on 17-Apr-2020 10:55:19