1. 题意
求一个序列和。序列 a a a满足:
- 大小为 n n n
- ∀ 0 ≤ i , j < n , i ≠ j , a i + a j ≠ t a r g e t \forall 0\le i,j \lt n,i \ne j,a_i+a_j \ne target ∀0≤i,j<n,i=j,ai+aj=target
找出美丽数组的最小和
2. 题解
贪心的构造这个序列。
当 n ≤ t a r g e t / 2 n \le target/2 n≤target/2时,依次累加序列即可。
当 n > t a r g e t / 2 n>target/2 n>target/2时,从 t a r g e t target target开始累加。
m = t a r g e t / 2 a n s = { n ( n + 1 ) / 2 n ≤ m m ( m + 1 ) / 2 + ( t a r g e t + t a r g e t + n − m − 1 ) ( n − m ) / 2 n > m m=target/2\\ ans= \begin{cases} n(n+1)/2 \quad n \le m\\ m(m+1)/2 +(target+target+n-m-1)(n-m)/2\quad n \gt m \end{cases} m=target/2ans={n(n+1)/2n≤mm(m+1)/2+(target+target+n−m−1)(n−m)/2n>m
- 代码
class Solution {
public:int minimumPossibleSum(int n, int target) {long long mid = target/2;long long MOD = 1e9+7;long long ans = 0;if (n <= mid) {ans = n % MOD * ((n + 1)%MOD)/2;}else {ans = (mid+1)*mid /2;ans %= MOD;long long cnt = n - mid;ans += (target + (target + cnt - 1)) * (cnt) /2; }// int idx = 1;// int ans = 0;// for (int i = 0; i < n; ++i,++idx) {// if ( i == mid )// idx = target;// ans += idx % MOD;// ans %= MOD;// }return (int) (ans % MOD); }
};