Sorting + modular combinatorics using Fermat's little theorem
Intuition
Sort and consider each element as the minimum and maximum value of all possible subsequences containing that element.
Count all possible subsequences
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
* Sort and consider each element as the minimum and maximum value of all possible subsequences containing that element.
* Count all possible subsequences where an element is minium/maximum.
# Approach
<!-- Describe your approach to solving the problem. -->
* Needs modular combinatorics using Fermat's little theorem. Precompute factorials and inverse factorials beforehand.
# Complexity
- Time complexity: $$O(NlogN))$$ due to sorting
<!-- Add your time complexity here, e.g. $$O(n)$$ -->  

- Space complexity: $$O(N)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```python3 []
class Solution:
    def minMaxSums(self, nums: List[int], k: int) -> int:
        mod = 10**9 + 7        
        fact = [1]
        invfact = [1]
        for i in range(1, len(nums) + 1):
            fact.append(fact[-1] * i % mod)
            invfact.append(pow(fact[-1], -1, mod))

        @cache
        def count(n):
            total = 0
            for r in range(min(n + 1, k)):
                nCr = fact[n] * invfact[r] * invfact[n-r] % mod
                total = (total + nCr) % mod
            return total
        
        nums.sort()
        ss = 0
        for i in range(len(nums)):
            minc = count(i)
            maxc = count(len(nums) - i - 1)
            ss = (ss + (minc + maxc) * nums[i]) % mod
        return ss
        
```
['Math', 'Sorting', 'Combinatorics', 'Python3']