Minimum increment in the sides required to get non-negative area of a triangle
Given three sides of the triangle, find the minimum increase in the length of the side of the triangle to make the area of the triangle non-negative.
Examples:
Input: a = 3, b = 4, c = 10
Output: 3
With the given sides, the area is negative.
If a is increased to 5 and b to 5, then the area becomes 0, which is not negative.
Input: a = 6, b = 6, c = 10
Output: 2
Approach: Since the area of any triangle is non-negative if the sum of the smallest two sides is always greater than or equal to the third side, hence the following steps should be followed to solve the above problem:
- Sort the three sides in increasing order.
- Check if the sum of the first two sides is greater than or equal to the third side, if it is, then the answer is 0.
- If it is not, then the answer will be (third side – (first side + second side)).
Below is the implementation of the given approach.
C++
#include <bits/stdc++.h>
using namespace std;
int minimumIncrease( int a, int b, int c)
{
int arr[] = { a, b, c };
sort(arr, arr + 3);
if (arr[0] + arr[1] >= arr[2])
return 0;
else
return arr[2] - (arr[0] + arr[1]);
}
int main()
{
int a = 3, b = 5, c = 10;
cout << minimumIncrease(a, b, c);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int minimumIncrease( int a, int b,
int c)
{
int arr[] = { a, b, c };
Arrays.sort(arr);
if (arr[ 0 ] + arr[ 1 ] >= arr[ 2 ])
return 0 ;
else
return arr[ 2 ] - (arr[ 0 ] + arr[ 1 ]);
}
public static void main (String[] args)
{
int a = 3 , b = 5 , c = 10 ;
System.out.println(minimumIncrease(a, b, c));
}
}
|
Python 3
def minimumIncrease(a, b, c) :
arr = [ a, b, c ]
arr.sort()
if arr[ 0 ] + arr[ 1 ] > = arr[ 2 ] :
return 0
else :
return arr[ 2 ] - (arr[ 0 ] + arr[ 1 ])
if __name__ = = "__main__" :
a, b, c = 3 , 5 , 10
print (minimumIncrease(a, b, c))
|
C#
using System;
class GFG
{
static int minimumIncrease( int a, int b,
int c)
{
int [] arr = { a, b, c };
Array.Sort(arr);
if (arr[0] + arr[1] >= arr[2])
return 0;
else
return arr[2] - (arr[0] + arr[1]);
}
public static void Main ()
{
int a = 3, b = 5, c = 10;
Console.Write(minimumIncrease(a, b, c));
}
}
|
PHP
<?php
function minimumIncrease( $a , $b , $c )
{
$arr = array ( $a , $b , $c );
sort( $arr );
if ( $arr [0] + $arr [1] >= $arr [2])
return 0;
else
return $arr [2] - ( $arr [0] + $arr [1]);
}
$a = 3;
$b = 5;
$c = 10;
echo minimumIncrease( $a , $b , $c );
?>
|
Javascript
<script>
function minimumIncrease(a , b , c)
{
var arr = [ a, b, c ];
arr.sort((a,b)=>a-b);
if (arr[0] + arr[1] >= arr[2])
return 0;
else
return arr[2] - (arr[0] + arr[1]);
}
var a = 3, b = 5, c = 10;
document.write(minimumIncrease(a, b, c));
</script>
|
complexity Analysis:
- Time Complexity: O(1)
- Auxiliary Space: O(1)
Last Updated :
05 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...