Problem Description
Given two positive integers n and target, construct an array nums of n pairwise distinct positive integers such that there do not exist two distinct indices i and j with nums[i] + nums[j] == target. We want to minimize the sum of nums (and return it modulo 10^9+7).
Key Insights
- The “conflict” arises only when two numbers from the array sum to target.
- In the range [1, target - 1] numbers naturally form pairs: (x, target - x). For each such pair (with x < target - x), only the smaller number is optimal to pick in order to minimize the overall sum.
- For target even the midpoint (target/2) is self‐conflicting only if picked twice – so one copy is allowed.
- The best strategy is to pick as many small “safe” numbers from 1 to target-1 (using only one number from each forbidden pair). If more numbers are needed, pick the next smallest numbers starting from target which are automatically safe.
- Use arithmetic progression formulas to get the sum and apply modulo operations to keep numbers in range.
Space and Time Complexity
Time Complexity: O(1) – all operations use constant time mathematical calculations. Space Complexity: O(1) – only a fixed number of variables are used.
Solution
We first determine the set S of “safe” numbers that we can choose from the range [1, target-1] without conflict. For each pair (i, target-i) for i from 1 to floor((target-1)/2), choose i. Additionally, if target is even, include target/2 as a “center” number because one instance is allowed.
Let m = floor((target-1)/2) and extra = 1 if target is even (else 0). Then safeCount = m + extra.
Case 1: n ≤ safeCount
– We can pick n numbers from S. Since S sorted starts with the smallest numbers, if n is entirely among the smallest ones (or in the case target is even, possibly including target/2 as the last element) the sum is computed accordingly.
• For example, if target is odd, S = [1, 2, …, m] so answer = n*(n+1)/2.
• For target even and if n equals m+1 (i.e. using all available safe elements), answer = (sum of 1 through m) + target/2.
Case 2: n > safeCount
– Use all safe numbers S first, and then choose the additional k2 = n − safeCount numbers from starting at target. These additional numbers are consecutive: target, target+1, …, target+k2-1.
– Their sum is: k2target + k2(k2-1)/2.
– Final answer is the sum of S plus the additional sum (all taken modulo 10^9+7).
We use arithmetic progression formulas and careful modulo arithmetic to handle large numbers.