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[] = { 1, 1, 1, 3, 3 };int result[] = maximumPerimeterTriangle(arr);System.out.println(Arrays.toString(result));}static int[] maximumPerimeterTriangle(int[] arr) {// sort the arrayArrays.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;} elsecontinue;}if (flag == 0)return new int[] { ans };elsereturn new int[] { x, y, z };}}
C++
#include <bits/stdc++.h>using namespace std;vector<int> maximumPerimeterTriangle(vector<int> arr){int n = arr.size();vector<int> res;//sort the arraysort(arr.begin(), arr.end());int ans = -1;int x = 0, y = 0, z = 0;int flag = 0;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;}elsecontinue;}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<int> arr = {1, 1, 1, 3, 3};vector<int> ans = maximumPerimeterTriangle(arr);for (int i = 0; i < ans.size(); i++){cout << ans[i] << " ";}return 0;}//Time Complexity: O(nlog(n))
No comments:
Post a Comment