Problem Description
Given an integer array nums and a positive integer k, you need to compute the total sum (modulo 10⁹+7) of the maximum and minimum elements for every subsequence of nums that contains at most k elements. (Note that a subsequence has elements in the original order; its size can range from 1 up to k.) For example, if a subsequence consists of a single element x then its minimum and maximum are both x and contribute 2*x to the total.
Key Insights
- Sorting the array helps in efficiently determining the number of times an element appears as the maximum or minimum in any valid subsequence.
- When the array is sorted, if an element at index i is chosen as the maximum, then any subset of elements chosen from the indices [0, i-1] (using up to k-1 additional elements) can form a subsequence.
- Similarly, if an element is chosen as the minimum, other elements must be chosen from the indices [i+1, n-1].
- The small bound on k (at most 70) allows us to sum combination values for each element in O(k) per element.
- Using precomputed factorials and inverse factorials, we can calculate binomial coefficients quickly without iterating fully over n.
Space and Time Complexity
Time Complexity: O(n * k) where n is the number of elements and k is at most 70. Space Complexity: O(n) for storing precomputed factorials and inverse factorials (plus additional O(n) space for sorting).
Solution
We first sort the input array. For each element in its sorted order:
- Compute the number of valid subsequences in which the element acts as the maximum. For an element at index i, you can choose any j (from 0 to min(k-1, i)) other elements from the first i elements (via C(i, j)).
- Compute the number of valid subsequences in which that same element acts as the minimum. For an element at index i, choose up to k-1 elements from the remaining n-i-1 elements (via C(n-i-1, j)).
- Multiply the element’s value by the sum of the two counts (each subsequence contributes the element’s value either as minimum or maximum; note that single element subsequences are counted twice).
- Sum these contributions modulo 10⁹+7.
Precomputing factorials and their modular inverses enables fast computation of the combination (binomial coefficient) C(n, r). Finally, we sum the contributions for all elements to obtain the answer.