HackerRank Maximum Perimeter Triangle Solution
In this post, we will solve HackerRank Maximum Perimeter Triangle Problem Solution.
Given an array of stick lengths, use 3 of them to construct a non-degenerate triangle with the maximum possible perimeter. Return an array of the lengths of its sides as 3 integers in non-decreasing order.
If there are several valid triangles having the maximum perimeter:
- Choose the one with the longest maximum side.
- If more than one has that maximum, choose from them the one with the longest minimum side.
- If more than one has that maximum as well, print any one them.
If no non-degenerate triangle exists, return [-1].
Example
sticks = [1, 2, 3, 4, 5, 10]
The triplet (1, 2, 3) will not form a triangle. Neither will (4, 5, 10) or (2, 3, 5), so the problem is reduced to (2, 3, 4) and (3, 4, 5). The longer perimeter is 3+ 4+5=12.
problem is reduced to and . The longer perimeter is .
Function Description
Complete the maximumPerimeterTriangle function in the editor below.
maximumPerimeterTriangle has the following parameter(s):
- int sticks[n]: the lengths of sticks available
Returns
- int[3] or int[1]: the side lengths of the chosen triangle in non-decreasing order or -1
Input Format
The first line contains single integer i, the size of array sticks.
The second line contains i space-separated integers sticks[i], each a stick length.
Sample Input 0
5
1 1 1 3 3
Sample Output 0
1 3 3
Explanation 0
There are 2 possible unique triangles:
- (1, 1, 1)
- (1,3,3)
The second triangle has the largest perimeter, so we print its side lengths on a new line in
non-decreasing order.
Maximum Perimeter Triangle C Solution
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n,count=0;
scanf("%d",&n);
int a[n];
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
for(int i=0;i<n-1;i++){
for(int j=1+i;j<n;j++){
int temp;
if(a[i]>a[j]){
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
for (int i=n-1;i>=2;i--){
if((a[i-2]+a[i-1]>a[i])){
printf("%d %d %d",a[i-2],a[i-1],a[i]);
count+=1;
break;
}
if((count==0)&&(i==2))
printf("-1");
}
return 0;
}
Maximum Perimeter Triangle C++ Solution
// ==========================================================================
//
// Starting by the name of Almighty Allah
//
// ==========================================================================
#include<bits/stdc++.h>
#include <algorithm>
#include <cstdio>
#include <sstream>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <set>
#include <queue>
#include <stack>
#include <list>
#include <iostream>
#include <fstream>
#include <numeric>
#include <string>
#include <vector>
#include <cstring>
#include <map>
#include <iterator>
#include <deque>
#include <climits>
#include <complex>
#include <bitset>
using namespace std;
#define LL long long
#define ULL unsigned long long
// I/O
#define I(X) scanf("%d", &(X))
#define II(X, Y) scanf("%d%d", &(X), &(Y))
#define III(X, Y, Z) scanf("%d%d%d", &(X), &(Y), &(Z))
#define IL(X) scanf("%lld", &X)
#define IIL(X,Y ) scanf("%lld%lld", &X,&Y)
#define IIIL(X,Y,Z) scanf("%lld%lld%lld", &X,&Y,&Z)
#define ID(x) scanf("%lf",&x)
#define IID(x,y) scanf("%lf%lf",&x,&y)
#define IIID(x,y,z) scanf("%lf%lf%lf",&x,&y,&z)
#define DI(X) int X; I(X);
#define DII(X, Y) int X, Y; II(X,Y)
#define DIII(X, Y, Z) int X, Y, Z; III(X,Y,Z);
#define DIL(X) LL X; IL(X)
#define DIIL(X,Y) LL X,Y; IIL(X,Y)
#define DIIIL(X,Y,Z) LL X,Y,Z; IIIL(X,Y,Z)
#define DDI(x) double x; ID(x);
#define DDII(x,y) double x,y; IID(x,y);
#define DDDII(x,y,z) double x,y,z; IIID(x,y,z);
#define SS(s) scanf("%s",s)
#define PI(x) printf("%d\n", x)
#define PII(x,y) printf("%d %d\n", x,y)
#define PIII(x,y,z) printf("%d %d %d\n",x,y,z)
#define PIL(x) printf("%lld\n", x)
#define PIIL(x,y) printf("%lld %lld\n", x,y)
#define PIIIL(x,y,z) printf("%lld %lld %lld\n",x,y,z)
// LOOP
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define rev(i,a,b) for(int i=a;i>=b;i--)
#define repv(i,a) for(int i=0;i<(int)a.size();i++)
#define revv(i,a) for(int i=((int)a.size())-1;i>=0;i--)
#define FS(x) for(typeof (x.begin()) it = x.begin(); it != x.end (); it++)
#define PR(x) for(typeof (x.begin()) it = x.begin(); it != x.end (); it++) { cout << *it << " "; } cout << endl;
// array initialization
#define MEM(a,val) memset(a,val,sizeof(a));
#define SET(a) memset(a,-1,sizeof a)
#define CLR(a) memset(a,0,sizeof a)
// min-max
#define Max(a,b) (a>b?a:b)
#define Min(a,b) (a<b?a:b)
#define _Max(a,b,c) Max(a,Max(b,c))
#define _Min(a,b,c) Min(a,Min(b,c))
#define MAX(a) (*max_element(all(a)))
#define MIN(a) (*min_element(all(a)))
#define FastMax(x,y) ((((y-x)>>(32-1))&(x^y))^y)
#define FastMin(x,y) ((((y-x)>>(32-1))&(x^y))^x)
#define SQR(n) ((n)*(n))
#define all(a) a.begin(),a.end()
#define PB push_back
#define NL puts("");
#define pline cout << "_________________________" << endl;
// pair
#define XX first
#define YY second
// binary search
#define LB(a,x) (lower_bound(all(a),x)-a.begin())
#define UB(a,x) (upper_bound(all(a),x)-a.begin())
//#define SI(X) X=in<int>()
//#define SII(X,Y) X=in<int>(),Y=in<int>()
//#define SIII(X,Y,Z) X=in<int>(),Y=in<int>(),Z=in<int>()
//
//#define SL(X) X=in<LL>()
//#define SLL(X,Y) X=in<LL>(),Y=in<LL>()
//#define SLLL(X,Y,Z) X=in<LL>(),Y=in<LL>(),Z=in<LL>()
//#define SEG int mid=(s+e)>>1,l=(idx<<1),r=(l|1);
#define in(l,x,r) ( l<=x && x<=r )
// Bit-op
#define countbit(x) __builtin_popcount(x)
//template< class T, class X > inline bool checkbit(T a, X pos) { T t=1;return ((a&(t<<pos))>0); }
//template< class T, class X > inline T setbit(T a, X pos) { T t=1;return (a|(t<<pos)); }
//template< class T, class X > inline T resetbit(T a, X pos) { T t=1;return (a&(~(t<<pos))); }
//template< class T, class X > inline T togglebit(T a, X pos) { T t=1;return (a^(t<<pos)); }
//// mathematics
//template<typename T> T POW(T base,T power) { T ret=1; while(power) { if(power & 1) ret=(ret*base); base=(base*base); power>>=1; }return ret; }
//template<typename T> T PPOW(T B,T P) { if(P==0) return 1; if(P&1) return B*POW(B,P-1); else return SQR(POW(B,P/2));}
//template<typename T> T Bigmod(T base,T power,T mod) { T ret=1; while(power) { if(power & 1) ret=(ret*base)%mod; base=(base*base)%mod; power>>=1; }return ret; }
//template<typename T> T ModInverse(T number,T mod) { return Bigmod(number,mod-2,mod); }
//template<typename T> T GCD(T a,T b) { if(a<0)return GCD(-a,b);if(b<0)return GCD(a,-b);return (b==0)?a:GCD(b,a%b);}
//template<typename T> T LCM(T a,T b) { if(a<0)return LCM(-a,b);if(b<0)return LCM(a,-b);return a*(b/GCD(a,b));}
//template<typename T> T EUCLIDE(T a,T b,T &x,T &y) { if(a<0){T d=euclide(-a,b,x,y);x=-x;return d;} if(b<0){T d=euclide(a,-b,x,y);y=-y;return d;} if(b==0){x=1;y=0;return a;}else{T d=euclide(b,a%b,x,y);T t=x;x=y;y=t-(a/b)*y;return d;}}
//template<typename T> T ABS(T a) { if(a<0)return -a;else return a;}
//// geometry
template<typename T> double DIS(T x1,T y1,T x2, T y2) { return sqrt( (double)( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) ) );}
//template<typename T> T ANGLE(T x1,T y1,T x2, T y2) { return atan( double(y1-y2) / double(x1-x2));}
//template<typename T> LL isLeft(T a,T b,T c) { return (c.x-a.x)*(b.y-a.y)-(b.x-a.x)*(c.y-a.y); }
//// Degree and Radian
////double DEG(double x) { return (180.0*x)/(M_PI*1.0);}
////double RAD(double x) { return (x*(M_PI*1.0))/(180.0);}
//
//// debug
//void P_ARR(int *ar,int a,int b) { if(a>b) swap(a,b); if(a<=b) cout << ar[a]; for(int i=a+1;i<=b;i++) cout << " "<<ar[i]; cout << endl; }
//template<typename T> T In(){ char ch; T n = 0; bool ng = false; while (1) { ch = getchar(); if (ch == '-') { ng = true; ch = getchar(); break;} if (ch>='0' && ch<='9') break; } while (1) { n = n*10 + (ch - '0'); ch = getchar(); if (ch<'0' || ch>'9') break; } return (ng?-n:n); }
//int month[]={31,28,31,30,31,30,31,31,30,31,30,31}; /// month
//int dir[5][2] = { {0,0},{1,0},{0,1},{-1,0},{0,-1} }; /// 4 Direction
//int dir[9][2] = { {0,0},{1,0},{0,1},{-1,0},{0,-1},{-1,1},{-1,-1},{1,-1},{1,1}}; /// 8 direction
//int dir[9][2] = { {0,0},{2,1},{1,2},{-1,2},{-2,1},{-2,-1},{-1,-2},{1,-2},{2,-1} }; /// Knight Direction
//int dir[8][2] = { {0,0},{2,0},{1,1},{-1,1} ,{-2,0} , {-1,-1} ,{1,-1} }; /// Hexagonal Direction
// dir[][0] = x value, dir[][1] = y value
/// ======================================================================================================
#define debug 0
#define AA if(debug)
#define eps (1e-7)
//#define pi (2.0*acos(0.0)) //#define PI acos(-1.0)
// IO
//#define READ freopen("C:\\Users\\backbencher\\Desktop\\input.txt","r",stdin)
//#define WRITE freopen("C:\\Users\\backbencher\\Desktop\\output.txt","w",stdout)
#define _cin ios_base::sync_with_stdio(0); cin.tie(0);
// 0123456789
#define MX 500007
#define MOD 1000000007
//#define inf 100000000
LL ar[107];
int main()
{
DI(n);
rep(i,1,n) cin>>ar[i];
sort( ar+1 , ar+1+n );
int flag = 0;
LL a,b,c;
LL mx = -1;
LL br[5];
rep(i,1,n)
{
rep(j,i+1,n)
{
rep(k,j+1,n)
{
if( ar[i]+ar[j]>ar[k] )
{
br[1] = ar[i];
br[2] = ar[j];
br[3] = ar[k];
sort( br+1 , br+1+3 );
LL tot = 0;
rep(ii,1,3) tot += br[ii];
if( tot>mx )
{
mx = tot;
a = br[1];
b = br[2];
c = br[3];
}
else if( tot==mx && c>br[3] )
{
mx = tot;
a = br[1];
b = br[2];
c = br[3];
}
else if( tot==mx && c==br[3] && a>br[1] )
{
mx = tot;
a = br[1];
b = br[2];
c = br[3];
}
}
}
}
}
if( mx==-1 ) cout << mx << endl;
else
{
cout << a << " " << b << " " << c << endl;
}
return 0;
}
Maximum Perimeter Triangle C Sharp Solution
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
string[] arr_temp = Console.ReadLine().Split(' ');
int[] arr = Array.ConvertAll(arr_temp,Int32.Parse);
int[] arr2 = arr.OrderByDescending(x => x).ToArray();
bool yes = false;
for (int i = 0; i < arr2.Length - 2; ++i)
{
if (arr2[i] < arr2[i + 1] + arr2[i + 2])
{
Console.WriteLine("{2} {1} {0}", arr2[i], arr2[i + 1], arr2[i + 2]);
yes = true;
break;
}
}
if(!yes)
{
Console.WriteLine(-1);
}
}
}
Maximum Perimeter Triangle Java Solution
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'maximumPerimeterTriangle' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts INTEGER_ARRAY sticks as parameter.
*/
public static List<Long> maximumPerimeterTriangle(List<Integer> sticks) {
sticks.sort(Integer::compareTo);
long maxPerimeter = -1L;
List<Long> result = new ArrayList<>();
for(int i = 0; i < sticks.size() - 2; ++i) {
long val = sticks.get(i) + sticks.get(i + 1);
if(val > sticks.get(i + 2) && maxPerimeter < val + sticks.get(i + 2)) {
result = new ArrayList<>(Arrays.asList((long) sticks.get(i), (long) sticks.get(i + 1), (long) sticks.get(i + 2)));
maxPerimeter = Math.max(maxPerimeter, val + sticks.get(i + 2));
}
}
if(maxPerimeter == -1) {
return Collections.singletonList(-1L);
}
return result;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<Integer> sticks = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Integer::parseInt)
.collect(toList());
List<Long> result = Result.maximumPerimeterTriangle(sticks);
bufferedWriter.write(
result.stream()
.map(Object::toString)
.collect(joining(" "))
+ "\n"
);
bufferedReader.close();
bufferedWriter.close();
}
}
Maximum Perimeter Triangle JavaScript Solution
function processData(input) {
var n = parseInt(input.split("\n")[0]);
var arr = input.split("\n")[1].split(" ").map(function(num){
return parseInt(num);
});
var perimeter = 0;
var triangle;
if(n > 2){
for(var x=0; x<arr.length-2; x++){
for(var y=x+1; y<arr.length-1; y++){
for(var z=y+1; z<arr.length; z++){
var a= arr[x];
var b= arr[y];
var c= arr[z];
if((a+b > c) && (a+c > b) && b+c > a){
if(perimeter < a+b+c){
perimeter = a+b+c;
triangle = [a, b, c];
}
}
}
}
}
}
if(perimeter == 0) console.log(-1);
else console.log(triangle.sort(function(a, b){return a-b}).join(" "));
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
Maximum Perimeter Triangle Python Solution
from itertools import combinations
n = int(input())
l = [int(x) for x in input().split()]
l.sort(reverse=True)
def solve():
possibles = list(combinations(l,3))
for possible in possibles:
x,y,z=map(int,possible)
if (x+y-z)*(y+z-x)*(z+x-y) > 0:
print (*(sorted([x,y,z])),sep=' ')
return
print (-1)
solve()