Find Maximum Perimeter triangle

Given an array of stick lengths, use 3 of them to construct a non-degenerate triangle with the maximum possible perimeter. Print the lengths of its sides as 3 space-separated integers in non-decreasing order.

If there are several valid triangles having the maximum perimeter:

1.Choose the one with the longest maximum side.

2.If more than one has that maximum, choose from them the one with the longest minimum side.

3.If more than one has that maximum as well, print any one of them.

If no non-degenerate triangle exists, print -1.

Example:

Input:  n=5,arr[1,1,1,3,3}
Output: 1 3 3

Approach:

Java


import java.util.Arrays;

public class FindMaxPerimeter {
    public static void main(String[] args) {

        int arr[] = { 11133 };
        int result[] = maximumPerimeterTriangle(arr);
        System.out.println(Arrays.toString(result));
    }

    static int[] maximumPerimeterTriangle(int[] arr) {
        // sort the array
        Arrays.sort(arr);
        int ans = -1;
        int x = 0, y = 0, z = 0;
        int flag = 0;
        int n = arr.length;
        for (int i = n - 2; i > 0; i--) {
            if (arr[i] + arr[i - 1] > arr[i + 1]) {
                x = arr[i - 1];
                y = arr[i];
                z = arr[i + 1];
                flag = 1;
                break;
            } else

                continue;
        }
        if (flag == 0)
            return new int[] { ans };
        else
            return new int[] { x, y, z };
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

vector<intmaximumPerimeterTriangle(vector<intarr)
{

    int n = arr.size();
    vector<intres;
    //sort the array

    sort(arr.begin(), arr.end());
    int ans = -1;
    int x = 0y = 0z = 0;
    int flag = 0;
    for (int i = n - 2i > 0i--)
    {
        if (arr[i] + arr[i - 1] > arr[i + 1])
        {
            x = arr[i - 1];
            y = arr[i];
            z = arr[i + 1];
            flag = 1;
            break;
        }
        else

            continue;
    }
    if (flag == 0)
        res.push_back(ans);
    else
    {
        res.push_back(x);
        res.push_back(y);
        res.push_back(z);
    }
    return res;
}

int main()
{
    int n = 5;

    vector<intarr = {11133};

    vector<intans = maximumPerimeterTriangle(arr);
    for (int i = 0i < ans.size(); i++)
    {
        cout << ans[i] << " ";
    }
    return 0;
}
//Time Complexity: O(nlog(n))



No comments:

Post a Comment