#3627
Maximum Median Sum of Subsequences of Size 3
MediumArrayMathGreedySortingGame TheoryGreedySorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
Sort the array and strategically select elements to maximize the median sum. The optimal choice is to take the largest two and the smallest one in each step.
⚙️
Algorithm
3 steps- 1Step 1: Sort the array in non-decreasing order.
- 2Step 2: Select elements starting from the end of the array, taking the last two and the first one in each group of three.
- 3Step 3: Sum the medians (the second largest of each selected triplet) to get the maximum median sum.
solution.py4 lines
1def maxMedianSum(nums):
2 nums.sort()
3 n = len(nums)
4 return sum(nums[n//3 + i] for i in range(n // 3))ℹ
Complexity note: Sorting the array takes O(n log n), and iterating through the array takes O(n), leading to an overall efficient solution.
- 1Sorting helps in easily accessing medians.
- 2Selecting strategically maximizes the sum.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.