题目要求
给你一个由长度为 n 的正整数 nums 组成的数组。
多边形是至少有 3 条边的封闭平面图形。多边形的最长边小于其他边之和。
相反,如果有 k 个(k >= 3)正实数 a1、a2、a3、...、ak,其中 a1 <= a2 <= a3 <= ... <= ak 且 a1 + a2 + a3 + ... + ak-1 > ak,则总是存在一个 k 边长为 a1,a2,a3,...,ak 的多边形。
多边形的周长是边长之和。
如果多边形的边可以由 nums 组成,则返回多边形的最大周长;如果无法创建多边形,则返回-1。
Example 1:
Input: nums = [5,5,5] Output: 15 Explanation: The only possible polygon that can be made from nums has 3 sides: 5, 5, and 5. The perimeter is 5 + 5 + 5 = 15.
Example 2:
Input: nums = [1,12,1,2,5,50,3] Output: 12 Explanation: The polygon with the largest perimeter which can be made from nums has 5 sides: 1, 1, 2, 3, and 5. The perimeter is 1 + 1 + 2 + 3 + 5 = 12. We cannot have a polygon with either 12 or 50 as the longest side because it is not possible to include 2 or more smaller sides that have a greater sum than either of them. It can be shown that the largest possible perimeter is 12.
Example 3:
Input: nums = [5,5,50] Output: -1 Explanation: There is no possible way to form a polygon from nums, as a polygon has at least 3 sides and 50 > 5 + 5.
思路
根据这个题目对于多边形的定义和描述,直觉上感觉是一道动态规划的题目。首先要做的事情依然是排序。排序之后我们的,我的的dp数组需要存储的是截止到nums中的第i个元素的最长多边形的周长(多边形的边数量需要大于等于3)。排序之后的数组从前向后自然满足了多边形的第一个条件。
第二这种方法要求我们需要存储以当前边为结尾的最长多边形的和,也就是意味着我们需要把当天的第i个元素视作是多边形的最长边,那么我们需要做的就是在之前所有元素中找到元素之和能够大于当前的最长边即可。
那么我们现在的核心问题就变成了如何判断这一点,我们只需要在存储dp的同时存储当前元素之前的所有元素之和即可。如果这个sum大于当前的nums[i],就意味着我们在满足条件1的同时也满足了条件2,即可以把nums[i]加入到多边形中,然后更新多边形的周长即可。
最后需要注意本题的数据体量和数值都比较大,使用int会超过范围,比如使用long long类型。
本题的hint中说使用贪心算法,我觉得贪心也可以写成递归的形式,逻辑是一致的就可以。
代码
class Solution {
public:long long largestPerimeter(vector<int>& nums) {sort(nums.begin(), nums.end());int n = nums.size();long long sum = 0;long long result = -1;vector<long long> dp(n, -1);for (int i = 0; i < n; ++i) {if (i > 1) {if (nums[i] < sum) {dp[i] = nums[i] + sum;result = max(dp[i], result);}}sum += nums[i];cout << sum << ' ' << nums[i] << endl;}return result;}
};
时间复杂度
排序大于dp,所以是O(nlogn)。
空间复杂度
维护dp数组即可,O(n)。