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 - Minimum Sum INPUT Parameters: n = 4 array size target = 6 forbidden sum Constraint: No two elements can sum to target (6) Forbidden Pairs: 1 + 5 2 + 4 3 + 3 Goal: Select 4 distinct positive integers, min sum ALGORITHM STEPS 1 Start with smallest: 1 Check: 6-1=5 (avoid 5) [1] 2 Add 2 Check: 6-2=4 (avoid 4) [1,2] 3 Add 3 Check: 6-3=3 (avoid dup) [1,2,3] 4 Skip 4,5 (forbidden) Add 6 instead [1,2,3,6] Selection Trace: 1 2 3 4 5 6 Selected Skipped FINAL RESULT Beautiful Array: 1 2 3 6 Sum Calculation: 1 + 2 + 3 + 6 Output: 12 Verification: 1+2=3 (OK) 1+3=4 (OK) 2+3=5 (OK) No pair sums to 6! Key Insight: Greedy approach: Always pick the smallest available number. For each number i, mark (target-i) as forbidden. This guarantees minimum sum since smaller numbers contribute less. Time: O(n), Space: O(n). TutorialsPoint - Find the Minimum Possible Sum of a Beautiful Array | Greedy Selection
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