Find the Minimum Possible Sum of a Beautiful Array - Problem

You are given positive integers n and target.

An array nums is beautiful if it meets the following conditions:

  • nums.length == n.
  • nums consists of pairwise distinct positive integers.
  • There doesn't exist two distinct indices, i and j, in the range [0, n - 1], such that nums[i] + nums[j] == target.

Return the minimum possible sum that a beautiful array could have modulo 109 + 7.

Input & Output

Example 1 — Basic Case
$ Input: n = 4, target = 6
Output: 12
💡 Note: One beautiful array is [1,3,4,6]. The pairs are (1,3), (1,4), (1,6), (3,4), (3,6) and (4,6). None sum to 6, so minimum sum is 1+3+4+6 = 14. But [1,2,4,7] gives 1+2+4+7 = 14, and [1,2,3,6] gives 1+2+3+6 = 12 which is smaller.
Example 2 — Small Target
$ Input: n = 2, target = 3
Output: 4
💡 Note: We need 2 distinct numbers where no pair sums to 3. We can take [1,3] since 1+3=4≠3, giving sum 4. Or [2,3] since 2+3=5≠3, but [1,3] has smaller sum.
Example 3 — Large Array
$ Input: n = 3, target = 3
Output: 8
💡 Note: Target is 3, so 1+2=3 is forbidden. We can take [1,3,4] but 1+2=3 so we can't take 2. Best is [1,3,4] giving sum 8.

Constraints

  • 1 ≤ n ≤ 105
  • 1 ≤ target ≤ 109

Visualization

Tap to expand
Beautiful Array Problem: n=4, target=6Available Numbers:12345672+4=6 ✗1+5=6 ✗Constraints:• Need exactly 4 numbers• All must be distinct positive integers• No two can sum to 6Solution Process:Selected: [1, 2, 3, 6]✓ All distinct ✓ No pairs sum to 6Minimum Sum: 1 + 2 + 3 + 6 = 12
Understanding the Visualization
1
Input
n=4 numbers needed, target=6 (forbidden sum)
2
Strategy
Greedily pick smallest numbers, avoid pairs summing to 6
3
Output
Beautiful array [1,2,3,6] with minimum sum 12
Key Takeaway
🎯 Key Insight: Greedily select smallest numbers while avoiding pairs that sum to target
Asked in
Google 15 Meta 12 Amazon 8
8.6K Views
Medium Frequency
~15 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen