Maximum and Minimum Sums of at Most Size K Subsequences Problem
Description
LeetCode Problem 3428.
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 most k elements.
Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: nums = [1,2,3], k = 2
Output: 24
Explanation:
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 24
The output would be 24.
Example 2:
Input: nums = [5,0,6], k = 1
Output: 22
Explanation:
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.
Example 3:
Input: nums = [1,1,1], k = 2
Output: 12
Explanation:
The subsequences [1, 1] and [1] each appear 3 times. For all of them, the minimum and maximum are both 1. Thus, the total is 12.
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 10^91 <= k <= min(70, nums.length)
Solution
Approach: Sorting + Combinatorics
Order does not matter for maximum and minimum, so sort the array. The element at sorted index i is the maximum of a subsequence when it is chosen together with up to k - 1 of the i elements before it, and the minimum when it is chosen with up to k - 1 of the n - 1 - i elements after it. (Ties are broken by position, so each subsequence is counted once.)
Let s[i] = C(i, 0) + C(i, 1) + ... + C(i, k - 1) be the number of ways to choose at most k - 1 of i elements. Then nums[i] contributes nums[i] * (s[i] + s[n - 1 - i]). We get all s[i] in O(n) from s[i + 1] = 2 * s[i] - C(i, k - 1), with the binomial coefficients computed from factorials and modular inverses.
Complexity: O(n log n) time for sorting and O(n) space.
class Solution:
def minMaxSums(self, nums: List[int], k: int) -> int:
mod = 10**9 + 7
n = len(nums)
nums = sorted(nums)
fact = [1] * (n + 1)
for i in range(1, n + 1):
fact[i] = fact[i - 1] * i % mod
inv = [1] * (n + 1)
inv[n] = pow(fact[n], mod - 2, mod)
for i in range(n, 0, -1):
inv[i - 1] = inv[i] * i % mod
def comb(a, b):
return 0 if b < 0 or b > a else fact[a] * inv[b] % mod * inv[a - b] % mod
# s[i] = number of ways to pick at most k - 1 of i elements = C(i,0) + ... + C(i,k-1),
# and s[i + 1] = 2 * s[i] - C(i, k - 1)
s = [1] * n
for i in range(1, n):
s[i] = (2 * s[i - 1] - comb(i - 1, k - 1)) % mod
ans = 0
for i, x in enumerate(nums):
# x is the maximum with i smaller elements to choose from, or the minimum with n-1-i larger ones
ans += x * (s[i] + s[n - 1 - i])
return ans % mod