Find the Minimum Possible Sum of a Beautiful Array Problem
#2834
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2834.
You are given positive integers n and target.
An array nums is beautiful if it meets the following conditions:
nums.length == n.numsconsists of pairwise distinct positive integers.- There doesn't exist two distinct indices,
iandj, in the range[0, n - 1], such thatnums[i] + nums[j] == target.
Return the minimum possible sum that a beautiful array could have modulo 10^9 + 7.
Example 1:
Input: n = 2, target = 3
Output: 4
Explanation: We can see that nums = [1,3] is beautiful.
- The array nums has length n = 2.
- The array nums consists of pairwise distinct positive integers.
- There doesn't exist two distinct indices, i and j, with nums[i] + nums[j] == 3.
It can be proven that 4 is the minimum possible sum that a beautiful array could have.
Example 2:
Input: n = 3, target = 3
Output: 8
Explanation: We can see that nums = [1,3,4] is beautiful.
- The array nums has length n = 3.
- The array nums consists of pairwise distinct positive integers.
- There doesn't exist two distinct indices, i and j, with nums[i] + nums[j] == 3.
It can be proven that 8 is the minimum possible sum that a beautiful array could have.
Example 3:
Input: n = 1, target = 1
Output: 1
Explanation: We can see, that nums = [1] is beautiful.
Constraints:
1 <= n <= 10^91 <= target <= 10^9
Solution
Approach: Greedy + Mathematics
Pick the smallest positive integers, skipping any x whose partner target - x has been picked. Let m = target / 2 (integer division). The numbers 1..m are all safe, since their partners are larger than m. If n <= m, the answer is 1 + 2 + ... + n. Otherwise take 1..m, then the next n - m integers starting from target. Sum both arithmetic series and take the result modulo 10^9 + 7.
Complexity: time O(1), space O(1).
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