#3428

Maximum and Minimum Sums of at Most Size K Subsequences

Medium
ArrayMathDynamic ProgrammingSortingCombinatoricsCombinatoricsSorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

The optimal solution leverages sorting and combinatorial mathematics to efficiently calculate the contributions of each element as both minimum and maximum in valid subsequences. By sorting the array, we can directly compute how many times each element contributes to the total sum without generating all subsequences.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the array nums.
  2. 2Step 2: For each element in the sorted array, calculate its contribution as a minimum and maximum in all valid subsequences.
  3. 3Step 3: Use combinatorial counting to determine how many subsequences of size up to k include the current element as min or max.
solution.py15 lines
1# Full working Python code
2from math import comb
3
4def max_min_sum(nums, k):
5    MOD = 10**9 + 7
6    nums.sort()
7    n = len(nums)
8    total_sum = 0
9
10    for i in range(n):
11        min_contrib = nums[i] * (comb(i, 0) + sum(comb(i, j) for j in range(1, k + 1))) % MOD
12        max_contrib = nums[i] * (comb(n - i - 1, 0) + sum(comb(n - i - 1, j) for j in range(1, k + 1))) % MOD
13        total_sum = (total_sum + min_contrib + max_contrib) % MOD
14
15    return total_sum

Complexity note: The optimal solution sorts the array in O(n log n) time, and then iterates through the array in O(n) time to calculate contributions, leading to an overall time complexity of O(n log n). The space complexity is O(1) since we only use a few variables.

  • 1Sorting the array allows for efficient calculation of contributions.
  • 2Using combinatorial mathematics reduces the need to generate all subsequences.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.