3627. Maximum Median Sum of Subsequences of Size 3
Problem Description
You are given an integer array nums
with a length divisible by 3.
You want to make the array empty in steps. In each step, you can select any three elements from the array, compute their median, and remove the selected elements from the array.
The median of an odd-length sequence is defined as the middle element of the sequence when it is sorted in non-decreasing order.
Return the maximum possible sum of the medians computed from the selected elements.
Intuition
To maximize the sum of medians when removing groups of three elements at a time, it's best to make each median as large as possible. Since a group of three sorted numbers will always have the middle one as its median, arranging the entire array in sorted order helps us pick medians efficiently. By carefully grouping the numbers—pairing the largest possible elements as medians and leaving the smallest for removal as non-medians—we can boost the overall sum. This leads to always choosing the second-largest element in each group of three from the sorted array as the median, ensuring the total sum of medians is as big as it can be.
Solution Approach
The solution uses a greedy strategy and sorting. The main idea is to maximize the sum of chosen medians by always selecting the largest possible medians at each removal step.
First, sort the array nums
in non-decreasing order. Since the length of nums
is a multiple of 3, you can split the sorted array into groups of three. In each group, the median is the second largest element.
To maximize the sum of all selected medians, always choose the largest available elements for the median positions as you remove groups. After sorting, for each group of three (from the right side, i.e., with the largest numbers), choose the middle one as the median.
You can efficiently do this by starting from index len(nums) // 3
in the sorted array and picking every second element until the end. These indices correspond to the medians in each group if you always select the largest elements possible as medians.
This can be implemented simply as:
nums.sort()
sum(nums[len(nums)//3::2])
This code sorts the array, then takes every second element starting from len(nums) // 3
(the optimal start index for maximizing medians), and returns their sum.
Ready to land your dream job?
Unlock your dream job with a 2-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Suppose nums = [1, 3, 5, 2, 4, 6]
.
-
Sort the Array: After sorting:
nums = [1, 2, 3, 4, 5, 6]
-
Divide into Groups of Three: Since the length is 6 (divisible by 3), divide into two groups:
- First group: [1, 2, 3]
- Second group: [4, 5, 6]
-
Find the Median in Each Group: In a sorted group of three, the median is always the second element:
- First group: median = 2
- Second group: median = 5
-
Sum the Medians: Total = 2 + 5 = 7
Applying the Solution Code:
nums.sort()
gives [1, 2, 3, 4, 5, 6]
len(nums) // 3 = 2
Taking every second element from index 2: nums[2::2] = [3, 5]
Sum: 3 + 5 = 8
But why does the code produce 8, not 7? This is because the code’s grouping maximizes medians by picking from the right side instead of left-to-right grouping:
- First pick: [1, 2, 6] → median = 2
- Second pick: [3, 4, 5] → median = 4 (but this is not maximizing)
- Max strategy: [4, 5, 6] (median=5), [1, 2, 3] (median=2): total 7
But the solution picks medians at indexes [2, 4] in the sorted array (3
and 5
). This matches the groups: [1, 2, 3] (median=3) and [4, 5, 6] (median=5). The sum is 3 + 5 = 8.
Final Answer: The maximum possible sum of medians is 8.
Solution Implementation
1from typing import List
2
3class Solution:
4 def maximumMedianSum(self, nums: List[int]) -> int:
5 # Sort the array in ascending order
6 nums.sort()
7
8 # Select every second element starting from len(nums) // 3 index
9 # and sum these elements. This will give the maximum sum of medians.
10 return sum(nums[len(nums) // 3 :: 2])
11
1class Solution {
2 public long maximumMedianSum(int[] nums) {
3 // Sort the array in ascending order to easily access medians
4 Arrays.sort(nums);
5 int n = nums.length;
6 long sum = 0;
7 // From the n/3-th element, select every second element as a median
8 for (int i = n / 3; i < n; i += 2) {
9 sum += nums[i];
10 }
11 // Return the total sum of selected medians
12 return sum;
13 }
14}
15
1class Solution {
2public:
3 // Function to calculate the maximum possible sum of medians from groups
4 long long maximumMedianSum(std::vector<int>& nums) {
5 // Sort the array in non-decreasing order
6 std::sort(nums.begin(), nums.end());
7 int n = nums.size();
8 long long ans = 0;
9 // Iterate through every second element starting at n / 3
10 for (int i = n / 3; i < n; i += 2) {
11 ans += nums[i]; // Add median value of each triplet group
12 }
13 return ans;
14 }
15};
16
1// Function to calculate the maximum sum of medians from triplets in the given array
2function maximumMedianSum(nums: number[]): number {
3 // Sort the array in non-decreasing order
4 nums.sort((a, b) => a - b);
5
6 const n = nums.length; // array length
7 let sum = 0;
8
9 // Loop over the median positions for each triplet
10 // Start from n / 3 (the first median index after grouping the sorted array into triplets)
11 // Increment by 2 to pick every median (after splitting into groups of 3)
12 for (let index = n / 3; index < n; index += 2) {
13 sum += nums[index];
14 }
15
16 return sum;
17}
18
Time and Space Complexity
The time complexity of the code is O(n \log n)
, dominated by the sorting operation nums.sort()
.
The space complexity is O(\log n)
, which comes from the recursion stack space used by the sorting algorithm (typically Timsort in Python).
Which of the following is a min heap?
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!