Problem 1626

Abstract / Summary

Choose a group of people with no skill conflicts to maximize total score.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1626.py

class Solution:
    def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:
        players = [ ( a, s ) for a, s in zip(ages, scores) ]
        players.sort(reverse = True) # oldest first, prefer higher score if same age

        @cache
        def deeper(i): # return team score if i is the lowest scoring player (and youngest)
            younger, lowscore = players[i]
            result = lowscore # new team with a single player

            for j in range(i):
                # check against all teams where all members have higher score
                # (they must be older or at least same age)
                older, highscore = players[j]
                if highscore >= lowscore:
                    result = max(result, lowscore + deeper(j)) # join team

            return result

        return max(deeper(i) for i in range(len(players)))
20 lines | 887 bytes | submitted January 22, 2024 | GitHub   42% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 51% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation computes the maximum possible total score of a team where each member’s age and score must satisfy the rule that a younger player cannot have a higher score than an older teammate. The algorithm first orders the players, then uses a memoized depth-first search to explore feasible team compositions, and finally selects the best result among all starting points.

Data Preparation

The function receives two parallel lists, scores and ages. It pairs each age with its corresponding score and stores the pairs in a list called players. The pairing is performed with a comprehension that iterates over the zipped input lists.

players = [(a, s) for a, s in zip(ages, scores)]

After pairing, the list is sorted in descending order of age, and for equal ages the higher score appears first because the tuple ordering places the score second. This ordering guarantees that any player encountered later in the list is either younger or of the same age with a lower or equal score, which aligns with the team-building constraint.

players.sort(reverse=True)   # oldest first, prefer higher score if same age

Recursive Scoring Function

A nested function deeper is defined and decorated with @cache, which automatically memoizes the results for each index. The function interprets the index i as the position of the youngest (or lowest-scoring) member of a candidate team. It begins by taking the score of the player at i as the baseline result, representing a team consisting solely of that player.

@cache
def deeper(i):
    younger, lowscore = players[i]
    result = lowscore

The function then iterates over all earlier indices j (players that are older or of the same age). For each such candidate, it checks whether the older player’s score is at least as large as the current player’s score. If the condition holds, the older player can be added to the team without violating the age-score rule. The recursive call deeper(j) yields the best score achievable with the older player as the youngest member of its sub-team, and the current player’s score is added to that value. The maximum of the existing result and the new combined score is stored back into result.

    for j in range(i):
        older, highscore = players[j]
        if highscore >= lowscore:
            result = max(result, lowscore + deeper(j))
    return result

Because the recursion always moves to a smaller index, the call graph forms a directed acyclic structure, ensuring termination.

Final Aggregation

After the memoized function is defined, the algorithm evaluates deeper(i) for every possible starting index i. The outer max call selects the highest team score among all configurations where each index serves as the youngest member.

return max(deeper(i) for i in range(len(players)))

Edge Cases

The sorting step naturally handles situations where multiple players share the same age. Since the sort is stable with respect to the score component, players of identical age are ordered from highest to lowest score, allowing the inner loop to consider only those with equal or greater scores. When scores are also identical, the condition highscore >= lowscore remains true, permitting any ordering of those players without breaking the rule.

If the input lists contain a single element, the comprehension creates a one-element players list, the recursion base case returns that single score, and the final max yields the same value, correctly representing the only possible team.

When all scores are decreasing with age, the inner condition will reject any younger-higher-score pair, and each recursive call will fall back to the base case, effectively treating every player as an isolated team. The outer max then picks the highest individual score, which is the optimal solution under the constraints.

If ages are strictly increasing while scores are non-decreasing, the condition will always succeed, allowing the recursion to accumulate the sum of all scores, which the algorithm correctly returns as the maximum team score.

Performance Optimizations

The most significant optimization is the use of the @cache decorator on the recursive function. By storing the result for each index after its first computation, the algorithm avoids recomputing overlapping sub-problems, turning an exponential exploration into a linear number of distinct states.

Sorting the players in descending order of age (and score) reduces the number of comparisons needed during recursion. Because the loop only iterates over earlier indices, the algorithm never revisits a pair of players that would violate the age ordering, eliminating unnecessary checks.

The combination of sorted ordering and memoization ensures that each pair of players is examined at most once, and each recursive call contributes directly to the final answer without redundant work. This design yields a highly efficient solution for the problem constraints.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a line of children wanting to form a basketball team. Each child has a skill score and an age. The goal is to pick a group so that nobody feels bad, meaning if someone is younger than a teammate, they must have a skill score that is lower than or equal to that teammate.

The first part of the code lines everyone up by their age. The oldest children go to the front of the line, and if two are the same age, the one with the higher score goes first.

Then, the code starts looking at each child one by one to see how big of a team can be built starting with them. To do this, it looks back at all the children who were placed earlier in the line. If one of those older children has a skill score that is just as good or better than the current child, it means they can be on the same team together.

It keeps checking these combinations to find the highest total score possible for any group. It remembers the scores of teams it has already looked at so it does not have to do the same work twice. Finally, it looks at all the possible teams it built and picks the one where the scores add up to the biggest amount.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.00 | σ = 1.25

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ JS Java Python Go TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
vthwang Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
vthwang Java
wisdompeak C++
26 links | 14 authors | 7 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

5 solutions   January 22, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality