Taro Logo

Maximum Points in an Archery Competition

Medium
Asked by:
Kakao
4 views
Topics:
ArraysRecursionDynamic ProgrammingGreedy Algorithms

Alice and Bob are opponents in an archery competition. The competition has set the following rules:

  1. Alice first shoots numArrows arrows and then Bob shoots numArrows arrows.
  2. The points are then calculated as follows:
    1. The target has integer scoring sections ranging from 0 to 11 inclusive.
    2. For each section of the target with score k (in between 0 to 11), say Alice and Bob have shot ak and bk arrows on that section respectively. If ak >= bk, then Alice takes k points. If ak < bk, then Bob takes k points.
    3. However, if ak == bk == 0, then nobody takes k points.
  • For example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points.

You are given the integer numArrows and an integer array aliceArrows of size 12, which represents the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize the total number of points he can obtain.

Return the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11. The sum of the values in bobArrows should equal numArrows.

If there are multiple ways for Bob to earn the maximum total points, return any one of them.

Example 1:

Input: numArrows = 9, aliceArrows = [1,1,0,1,0,0,2,1,0,1,2,0]
Output: [0,0,0,0,1,1,0,0,1,2,3,1]
Explanation: The table above shows how the competition is scored. 
Bob earns a total point of 4 + 5 + 8 + 9 + 10 + 11 = 47.
It can be shown that Bob cannot obtain a score higher than 47 points.

Example 2:

Input: numArrows = 3, aliceArrows = [0,0,1,0,0,0,0,0,0,0,0,2]
Output: [0,0,0,0,0,0,0,0,1,1,1,0]
Explanation: The table above shows how the competition is scored.
Bob earns a total point of 8 + 9 + 10 = 27.
It can be shown that Bob cannot obtain a score higher than 27 points.

Constraints:

  • 1 <= numArrows <= 105
  • aliceArrows.length == bobArrows.length == 12
  • 0 <= aliceArrows[i], bobArrows[i] <= numArrows
  • sum(aliceArrows[i]) == numArrows

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the size of the `aliceArrows` array, and what is the maximum value of `numArrows`?
  2. If there are multiple optimal distributions of arrows that yield the same maximum score, does it matter which one I return?
  3. How should leftover arrows (if any remain after achieving the maximum score) be distributed, or can they simply be placed in the 0-th section?
  4. Is the length of `aliceArrows` guaranteed to be fixed (e.g., 12 sections corresponding to standard archery scoring zones), or can it vary?
  5. Can `numArrows` be less than the total number of arrows Alice used, and how should we handle cases where we cannot win any sections?

Brute Force Solution

Approach

To solve this archery competition puzzle using the brute force method, we need to explore every single possible way Alice could allocate her arrows across all the target sections. By checking every combination, we can figure out which choice yields the highest total score while keeping track of how many arrows she has left.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the first scoring section and imagine every possible number of arrows Alice could shoot there, from zero all the way up to one more than what Bob shot.
  2. For each of those possibilities, move on to the next scoring section and again try every possible number of arrows she could shoot there.
  3. Keep doing this for all the remaining scoring sections until you have mapped out a complete plan of arrow counts for every single section.
  4. Check each complete plan to make sure the total number of arrows used does not exceed the total number of arrows Alice is given in the competition.
  5. If a plan uses too many arrows, throw it out because it is not a legal option.
  6. For every legal plan, calculate Alice's total score by adding up the points for every section where she managed to shoot more arrows than Bob.
  7. Compare the scores of all the valid plans you checked, and select the plan that gives Alice the absolute highest total points.

Code Implementation

def maximumBobPoints(numArrows, aliceArrows):
    maxScore = -1
    bestAllocation = []

    def explore(sectionIndex, arrowsLeft, currentScore, currentAllocation):
        nonlocal maxScore, bestAllocation
        if sectionIndex == 12:
            if currentScore > maxScore:
                maxScore = currentScore
                bestAllocation = list(currentAllocation)
                bestAllocation[0] += arrowsLeft
            return

        # We explore every valid arrow count to find the optimal point-scoring combination
        requiredArrows = aliceArrows[sectionIndex] + 1
        if arrowsLeft >= requiredArrows:
            currentAllocation.append(requiredArrows)
            explore(sectionIndex + 1, arrowsLeft - requiredArrows, currentScore + sectionIndex, currentAllocation)
            currentAllocation.pop()

        currentAllocation.append(0)
        explore(sectionIndex + 1, arrowsLeft, currentScore, currentAllocation)
        currentAllocation.pop()

    explore(0, numArrows, 0, [])
    return bestAllocation

Big(O) Analysis

Time Complexity
O(2ⁿ) – The brute force approach uses recursion to branch into multiple choices for each of the 12 scoring sections, where n represents the number of target sections. At each section, Alice can either choose to beat Bob by using one more arrow than him or score zero by using no arrows. This creates a binary decision tree with a depth of 12, resulting in approximately 2¹² branches or operations. When generalizing this to n target sections, the total operations scale exponentially as 2ⁿ, which simplifies to O(2ⁿ).
Space Complexity
O(N) – The auxiliary space complexity is driven by the recursive backtracking calls exploring arrow allocations across the scoring sections, reaching a maximum recursion depth equal to the number of sections N. Additionally, a temporary array of size N is maintained to track the current arrow distribution plan, alongside an array to store the best valid plan found so far. Therefore, the extra memory used by the recursion stack and the tracking arrays scales linearly with N, simplifying to Big O of N.

Optimal Solution

Approach

To find the maximum possible score in the archery competition, we can use a clever search strategy that decides whether or not to target each scoring zone. By exploring the choices of either trying to win a zone or skipping it, we can find the combination that yields the highest total points while staying within our arrow limit.

Here's how the algorithm would work step-by-step:

  1. Imagine you are walking through a series of scoring zones from the highest value down to the lowest, deciding how many arrows to spend in each zone.
  2. For any given zone, you have two main choices: either use one more arrow than your opponent used to win all the points for that zone, or completely ignore the zone and save all your arrows for other opportunities.
  3. If you decide to target a zone, you must commit enough arrows to beat your opponent, and keep track of how many arrows you have left to spend in the remaining zones.
  4. If you ever find yourself with arrows left over after considering all the zones, simply dump the remaining arrows into the lowest-value zone so no arrows are wasted.
  5. As you explore these choices, keep a running total of the points you accumulate and remember the specific arrow distribution that gave you the highest score.
  6. Whenever you finish checking a path of choices, compare your total points against the best score you have found so far and keep the better one.
  7. By systematically exploring whether to contest or skip each zone, you efficiently discover the winning strategy that maximizes your total points without needing to blindly guess every single possibility.

Code Implementation

class Solution:
    def maximum_bob_points(self, total_num_arrows: int, alice_arrow_counts: list[int]) -> list[int]:
        maximum_points_found = -1
        best_arrow_distribution = []

        def explore_scoring_zones(zone_index: int, arrows_remaining: int, current_points: int, current_distribution: list[int]):
            nonlocal maximum_points_found, best_arrow_distribution
            
            if zone_index < 0 or arrows_remaining == 0:
                if arrows_remaining > 0:
                    current_distribution[0] += arrows_remaining
                
                if current_points > maximum_points_found:
                    maximum_points_found = current_points
                    best_arrow_distribution = list(current_distribution)
                
                if arrows_remaining > 0:
                    current_distribution[0] -= arrows_remaining
                return

            # We explore winning the current zone if we have enough arrows to beat Alice. 
            arrows_needed = alice_arrow_counts[zone_index] + 1
            if arrows_remaining >= arrows_needed:
                current_distribution[zone_index] = arrows_needed
                explore_scoring_zones(zone_index - 1, arrows_remaining - arrows_needed, current_points + zone_index, current_distribution)
                current_distribution[zone_index] = 0

            # We also explore skipping the current zone to save arrows for higher-value targets.
            explore_scoring_zones(zone_index - 1, arrows_remaining, current_points, current_distribution)

        initial_distribution = [0] * 12
        explore_scoring_zones(11, total_num_arrows, 0, initial_distribution)
        return best_arrow_distribution

Big(O) Analysis

Time Complexity
O(2^n) – In this archery competition problem, the input size is represented by the number of scoring zones, which is fixed at n = 12. For each of the 12 zones, our recursive search explores two distinct choices: either contesting the zone by using one more arrow than the opponent or completely skipping the zone. This binary decision tree branches at each of the 12 levels, leading to approximately 2^n total paths or function calls to evaluate. Since n is a constant 12 in the constraints, this evaluates to a maximum of 2^12 or 4096 operations, which in general algorithmic terms simplifies to O(2^n).
Space Complexity
O(1) – The auxiliary space complexity is driven by the recursive function call stack and variables tracking the current arrow distribution, maximum points, and best path. Since the scoring zones are fixed to a constant size of 12 (from 0 to 11 points), the recursion depth is strictly bounded at 12 levels regardless of the total arrow count. Furthermore, the temporary lists used to store arrow counts always contain exactly 12 elements. Therefore, the extra memory usage is constant with respect to the input, simplifying to Big O notation of O(1).

Edge Cases

Zero arrows available (numArrows = 0)
How to Handle:
The algorithm will score 0 points by allocating 0 arrows to all sections and return the bobArrows array with all zeros.
Alice shoots 0 arrows in all sections
How to Handle:
Bob can win every section by allocating just 1 arrow to section 0 and 0 arrows elsewhere, maximizing his score.
Alice shoots heavily in higher sections while Bob has few arrows
How to Handle:
The DP or backtracking approach naturally prioritizes sections that yield the highest score-to-cost ratio for Bob.
Multiple sections require more arrows than Bob has total
How to Handle:
The subset generation will only evaluate combinations whose total arrow count does not exceed numArrows.
Tie in points with multiple valid arrow distributions
How to Handle:
Any valid combination achieving the maximum score is acceptable, but the algorithm can use a tie-breaker such as prioritizing lower sections.
Maximum number of sections (exactly 12 sections as defined by archery rules)
How to Handle:
Since the number of sections is fixed at 12, a 2^12 subset enumeration runs in a fraction of a millisecond and scales effortlessly.
Leftover unspent arrows after maximizing score
How to Handle:
Any remaining arrows can be safely dumped into section 0 since section 0 yields zero points and does not affect the optimal score.
Exact arrow budget match where every section requires arrows
How to Handle:
The algorithm correctly evaluates whether winning a subset of sections fits strictly within the exact arrow budget without overflow.