LeetCode 2971: Find Polygon With the Largest Perimeter Solution
Master LeetCode problem 2971 (Find Polygon With the Largest Perimeter), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2971. Find Polygon With the Largest Perimeter
Problem Explanation
Explanation
To find the largest possible perimeter of a polygon that can be formed using sides from the given array nums, we need to consider the largest sides first in order to maximize the perimeter. We can achieve this by sorting the array in descending order and then iterating over the sorted array to check if any set of consecutive sides can form a valid polygon.
Algorithm:
- Sort the input array
numsin descending order. - Iterate over the sorted array from index 0 to n-3 (to have at least 3 sides to form a polygon).
- Check if the current triplet of sides can form a valid polygon (largest side < sum of other two sides).
- If a valid polygon can be formed, return the perimeter.
- If no valid polygon can be formed, return -1.
Time Complexity: O(n log n) for sorting the array, where n is the number of elements in the input array. Space Complexity: O(1) as we are using constant extra space for variables.
Solution Code
import java.util.Arrays;
class Solution {
public int largestPerimeter(int[] nums) {
Arrays.sort(nums);
for (int i = nums.length - 3; i >= 0; i--) {
if (nums[i] + nums[i + 1] > nums[i + 2]) {
return nums[i] + nums[i + 1] + nums[i + 2];
}
}
return -1;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2971 (Find Polygon With the Largest Perimeter)?
This page provides optimized solutions for LeetCode problem 2971 (Find Polygon With the Largest Perimeter) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2971 (Find Polygon With the Largest Perimeter)?
The time complexity for LeetCode 2971 (Find Polygon With the Largest Perimeter) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2971 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2971 in Java, C++, or Python.