You are given an integer array nums and a positive integer k. Return the sum of the maximum and minimum elements of all subsequences of
nums with at mostk elements.
Since the answer may be very large, return it modulo10^9 + 7.
Input: nums =[1,2,3], k =2Output: 24Explanation:
The subsequences of `nums`with at most 2 elements are:**Subsequence**| Minimum | Maximum | Sum
---|---|---|---`[1]`|1|1|2`[2]`|2|2|4`[3]`|3|3|6`[1, 2]`|1|2|3`[1, 3]`|1|3|4`[2, 3]`|2|3|5**Final Total**|||24The output would be 24.
Input: nums =[5,0,6], k =1Output: 22Explanation:
For subsequences with exactly 1 element, the minimum and maximum values are
the element itself. Therefore, the total is`5 + 5 + 0 + 0 + 6 + 6 = 22`.
Input: nums =[1,1,1], k =2Output: 12Explanation:
The subsequences `[1, 1]` and `[1]` each appear 3 times. For all of them, the
minimum and maximum are both 1. Thus, the total is12.
For each element, count how many subsequences of size up to k have it as the minimum or maximum. If the array is sorted, for each index, the number of ways to pick elements to the left and right (up to k-1) gives the count. Use combinatorics and fast exponentiation to efficiently compute the sum for all possible subsequence sizes.
classSolution {
publicintsumOfMaxAndMin(int[] nums, int k) {
int MOD = 1_000_000_007, n = nums.length;
Arrays.sort(nums);
long[] pow2 =newlong[n+1];
pow2[0]= 1;
for (int i = 1; i <= n; i++) pow2[i]= pow2[i-1]* 2 % MOD;
long ans = 0;
for (int i = 0; i < n; i++) {
long cnt_max = pow2[i];
long cnt_min = pow2[n-i-1];
ans = (ans + (cnt_max - cnt_min + MOD) % MOD * nums[i]% MOD) % MOD;
}
return (int)ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funsumOfMaxAndMin(nums: IntArray, k: Int): Int {
val MOD = 1_000_000_007
val n = nums.size
nums.sort()
val pow2 = LongArray(n+1) { 1L }
for (i in1..n) pow2[i] = pow2[i-1] * 2 % MOD
var ans = 0Lfor (i in0 until n) {
val cnt_max = pow2[i]
val cnt_min = pow2[n-i-1]
ans = (ans + (cnt_max - cnt_min + MOD) % MOD * nums[i] % MOD) % MOD
}
return ans.toInt()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defsumOfMaxAndMin(self, nums: list[int], k: int) -> int:
MOD =10**9+7 n = len(nums)
nums.sort()
pow2 = [1]*(n+1)
for i in range(1, n+1):
pow2[i] = pow2[i-1]*2% MOD
ans =0for i in range(n):
cnt_max = pow2[i]
cnt_min = pow2[n-i-1]
ans = (ans + (cnt_max - cnt_min) * nums[i]) % MOD
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
impl Solution {
pubfnsum_of_max_and_min(nums: Vec<i32>, k: i32) -> i32 {
constMOD: i64=1_000_000_007;
letmut nums = nums;
nums.sort();
let n = nums.len();
letmut pow2 =vec![1i64; n+1];
for i in1..=n {
pow2[i] = pow2[i-1] *2%MOD;
}
letmut ans =0i64;
for i in0..n {
let cnt_max = pow2[i];
let cnt_min = pow2[n-i-1];
ans = (ans + (cnt_max - cnt_min +MOD) %MOD* nums[i] asi64%MOD) %MOD;
}
ans asi32 }
}