Input: n =2, target =3Output: 4Explanation: 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 4is the minimum possible sum that a beautiful array could have.
Input: n =3, target =3Output: 8Explanation: 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 8is the minimum possible sum that a beautiful array could have.
To minimize the sum, pick the smallest possible distinct positive integers, but avoid pairs that sum to target. The best way is to pick numbers from 1 upwards, skipping any number that would form a forbidden pair with a previously chosen number.
classSolution {
publicintminimumPossibleSum(int n, int target) {
finalint MOD = 1_000_000_007;
Set<Integer> used =new HashSet<>();
long sum = 0;
for(int x=1, cnt=0; cnt<n; ++x) {
if(used.contains(target-x)) continue;
sum = (sum + x) % MOD;
used.add(x);
++cnt;
}
return (int)sum;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funminimumPossibleSum(n: Int, target: Int): Int {
val MOD = 1_000_000_007
val used = mutableSetOf<Int>()
var sum = 0L; var cnt = 0var x = 1while (cnt < n) {
if ((target-x) in used) { x++; continue }
sum = (sum + x) % MOD
used.add(x)
cnt++ x++ }
return sum.toInt()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defminimumPossibleSum(self, n: int, target: int) -> int:
MOD =10**9+7 used = set()
ans =0 x =1while n:
if target-x notin used:
ans = (ans + x) % MOD
used.add(x)
n -=1 x +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnminimum_possible_sum(n: i32, target: i32) -> i32 {
letmut used = std::collections::HashSet::new();
letmut sum =0i64;
letmut cnt =0;
letmut x =1;
while cnt < n {
if!used.contains(&(target-x)) {
sum = (sum + x asi64) %1_000_000_007;
used.insert(x);
cnt +=1;
}
x +=1;
}
sum asi32 }
}