LeetCode 3635 - Earliest Finish Time for Land and Water Rides II
Great! We will cover LeetCode 3627 - Maximum Median Sum of Subsequences of Size 3 in a full, comprehensive technical guide following your formatting requirements. The problem gives us an integer array nums with a length divisible by 3.
Difficulty: 🟡 Medium
Topics: Array, Two Pointers, Binary Search, Greedy, Sorting
Solution
Great! We will cover LeetCode 3627 - Maximum Median Sum of Subsequences of Size 3 in a full, comprehensive technical guide following your formatting requirements.
Problem Understanding
The problem gives us an integer array nums with a length divisible by 3. We are asked to remove the array in steps by selecting any three elements, calculating their median, and removing them. The median of three numbers is the middle value when sorted. Our goal is to maximize the sum of all medians obtained during these removals.
The input is a simple integer array, and the output is a single integer representing the maximum possible sum of medians. The constraints are:
1 <= nums.length <= 5 * 10^5, which allows arrays up to half a million elements, so brute-force enumeration is infeasible.nums.length % 3 == 0, guaranteeing we can always partition the array into groups of three.1 <= nums[i] <= 10^9, indicating large integer values, but no negative numbers.
Important edge cases to consider:
- Arrays with repeated numbers (e.g.,
[1,1,10,10,10,10]). - Arrays already sorted or reverse sorted.
- Arrays where all elements are the same (median is always the same).
This ensures we must find a solution that can scale to hundreds of thousands of elements efficiently.
Approaches
Brute Force Approach
The brute-force approach would attempt all possible triplet selections for each step, computing the median and recursively calculating the maximum sum. For n elements, this involves selecting n choose 3 combinations repeatedly. This approach is correct but exponentially slow, with time complexity far exceeding the input limits (O((n!) / ((3!)^(n/3)))), so it is not feasible.
Optimal Approach
The key insight is sorting. Consider the array sorted in non-decreasing order. If we pair the largest numbers with smaller numbers, the largest number will often be discarded as the largest of the triplet, and the median will be the second largest in the triplet. To maximize the median sum:
- Sort the array.
- Repeatedly take the middle element of the largest remaining triplet.
- The maximum sum is obtained by picking the second largest element from the last two-thirds of the sorted array, skipping the largest element each time to avoid wasting the largest on a median.
In other words, for an array sorted as a1 <= a2 <= ... <= a3k, we pick every second element from the last 2k elements starting from the second largest triplet.
This approach works because the median of three numbers is always the middle value, so pairing a very large number with the smallest numbers would waste the largest number, while pairing strategically ensures the middle number is as large as possible.
| Approach | Time Complexity | Space Complexity | Notes |
|---|---|---|---|
| Brute Force | O((n choose 3)^(n/3)) | O(n) | Enumerate all triplets recursively, infeasible |
| Optimal | O(n log n) | O(1) or O(n) | Sort array, pick every second element from largest remaining triplets |
Algorithm Walkthrough
-
Sort the array
numsin non-decreasing order. -
Let
n = len(nums). -
Initialize a variable
median_sum = 0to accumulate the result. -
Set an index
i = n - 2. This points to the first median to pick from the sorted array (second largest element). -
Repeat
n // 3times (because we remove 3 elements each step): -
Add
nums[i]tomedian_sum. -
Decrement
iby 2 to skip the largest element and pick the next median. -
Return
median_sum.
Why it works: Sorting guarantees that we know the relative ordering of all elements. By always skipping the largest element and picking the second largest in the remaining subset, we maximize the contribution to the median sum. This invariant holds for every triplet chosen, ensuring global optimality.
Python Solution
from typing import List
class Solution:
def maximumMedianSum(self, nums: List[int]) -> int:
nums.sort()
n = len(nums)
median_sum = 0
i = n - 2 # start from the second largest element
for _ in range(n // 3):
median_sum += nums[i]
i -= 2 # skip the largest element
return median_sum
Implementation Walkthrough: We sort nums, then iterate n//3 times because there are n/3 triplets. At each iteration, nums[i] gives the median of the optimal triplet, and i is decremented by 2 to jump over the largest number. This approach avoids using extra space and handles large inputs efficiently.
Go Solution
import "sort"
func maximumMedianSum(nums []int) int64 {
sort.Ints(nums)
n := len(nums)
var medianSum int64 = 0
i := n - 2
for k := 0; k < n/3; k++ {
medianSum += int64(nums[i])
i -= 2
}
return medianSum
}
Go Notes: We use sort.Ints to sort the array. Since integers can be up to 10^9 and n can be large, we store the sum in int64 to avoid overflow. The logic is identical to Python.
Worked Examples
Example 1: nums = [2,1,3,2,1,3]
Sorted array: [1,1,2,2,3,3]
| Step | Pick Index | Median | Median Sum |
|---|---|---|---|
| 1 | 4 | 3 | 3 |
| 2 | 2 | 2 | 5 |
Output: 5
Example 2: nums = [1,1,10,10,10,10]
Sorted array: [1,1,10,10,10,10]
| Step | Pick Index | Median | Median Sum |
|---|---|---|---|
| 1 | 4 | 10 | 10 |
| 2 | 2 | 10 | 20 |
Output: 20
Complexity Analysis
| Measure | Complexity | Explanation |
|---|---|---|
| Time | O(n log n) | Sorting dominates; then we iterate n/3 times |
| Space | O(1) or O(n) | Sorting may require O(n) space depending on language |
Sorting is the bottleneck, and the rest of the algorithm is linear, making it efficient for up to 5*10^5 elements.
Test Cases
# Provided examples
assert Solution().maximumMedianSum([2,1,3,2,1,3]) == 5 # Example 1
assert Solution().maximumMedianSum([1,1,10,10,10,10]) == 20 # Example 2
# Edge cases
assert Solution().maximumMedianSum([1,1,1]) == 1 # smallest possible triplet
assert Solution().maximumMedianSum([1,2,3]) == 2 # ascending order
assert Solution().maximumMedianSum([3,2,1]) == 2 # descending order
assert Solution().maximumMedianSum([5]*300000) == 5*100000 # large input, all same
assert Solution().maximumMedianSum([i for i in range(1, 10)]) == 14 # mix small numbers
| Test | Why |
|---|---|
[2,1,3,2,1,3] |
Standard example with duplicates |
[1,1,10,10,10,10] |
Large numbers and duplicates |
[1,1,1] |
Minimal array size |
[1,2,3] |
Ascending order |
[3,2,1] |
Descending order |
[5]*300000 |
Large array, all same numbers |
[1..9] |
Odd/even patterns |
Edge Cases
All elements identical: In arrays like [5,5,5,5,5,5], all medians are the same. Our approach correctly picks any triplets; the median sum is always median * n/3.
Large inputs: The algorithm efficiently handles n = 5*10^5 with large values (10^9) because we sort and iterate, using only an integer accumulator.
Sorted or reverse-sorted arrays: Sorting ensures the algorithm does not depend on the initial ordering. Whether ascending or descending, the largest medians are correctly selected.
This completes a fully detailed, production-ready solution guide for LeetCode 3627 - Maximum Median Sum of Subsequences of Size 3.