LeetCode 题解工作台
找出美丽数组的最小和
给你两个正整数: n 和 target 。 如果数组 nums 满足下述条件,则称其为 美丽数组 。 nums.length == n . nums 由两两互不相同的正整数组成。 在范围 [0, n-1] 内, 不存在 两个 不同 下标 i 和 j ,使得 nums[i] + nums[j] == …
2
题型
7
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
我们可以贪心地从 $x = 1$ 开始构造数组 ,每次选择 ,并且排除 $target - x$。 我们不妨记 $m = \left\lfloor \frac{target}{2} \right\rfloor$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你两个正整数:n 和 target 。
如果数组 nums 满足下述条件,则称其为 美丽数组 。
nums.length == n.nums由两两互不相同的正整数组成。- 在范围
[0, n-1]内,不存在 两个 不同 下标i和j,使得nums[i] + nums[j] == target。
返回符合条件的美丽数组所可能具备的 最小 和,并对结果进行取模 109 + 7。
示例 1:
输入:n = 2, target = 3 输出:4 解释:nums = [1,3] 是美丽数组。 - nums 的长度为 n = 2 。 - nums 由两两互不相同的正整数组成。 - 不存在两个不同下标 i 和 j ,使得 nums[i] + nums[j] == 3 。 可以证明 4 是符合条件的美丽数组所可能具备的最小和。
示例 2:
输入:n = 3, target = 3 输出:8 解释: nums = [1,3,4] 是美丽数组。 - nums 的长度为 n = 3 。 - nums 由两两互不相同的正整数组成。 - 不存在两个不同下标 i 和 j ,使得 nums[i] + nums[j] == 3 。 可以证明 8 是符合条件的美丽数组所可能具备的最小和。
示例 3:
输入:n = 1, target = 1 输出:1 解释:nums = [1] 是美丽数组。
提示:
1 <= n <= 1091 <= target <= 109
解题思路
方法一:贪心 + 数学
我们可以贪心地从 开始构造数组 ,每次选择 ,并且排除 。
我们不妨记 。
如果 ,那么我们可以选择的数有 ,所以数组的和为 。
如果 ,那么我们可以选择的数有 ,共 个数,以及 个从 开始的数,所以数组的和为 。
注意,我们需要对结果取模 。
时间复杂度 ,空间复杂度 。
class Solution:
def minimumPossibleSum(self, n: int, target: int) -> int:
mod = 10**9 + 7
m = target // 2
if n <= m:
return ((1 + n) * n // 2) % mod
return ((1 + m) * m // 2 + (target + target + n - m - 1) * (n - m) // 2) % mod
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate demonstrates understanding of greedy algorithms.
- question_mark
The candidate applies the concept of invariant validation correctly.
- question_mark
The candidate is mindful of the problem's constraints and uses the modulo operation effectively.
常见陷阱
外企场景- error
Selecting numbers that violate the sum condition.
- error
Failing to ensure all integers are distinct.
- error
Incorrectly handling large values of n and target within the constraints.
进阶变体
外企场景- arrow_right_alt
What if we allow non-distinct integers in the array?
- arrow_right_alt
How would the approach change if n was significantly larger?
- arrow_right_alt
What if we needed to minimize the product instead of the sum?