Maximum Points in an Archery Competition — LeetCode 2212 Python Solution

MediumBit ManipulationArrayBacktrackingEnumeration
Problem
#2212
Reading time
4 min

The problem

Alice and Bob are opponents in an archery competition. The competition has set the following rules: Alice first shoots numArrows arrows and then Bob shoots numArrows arrows.

Example

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.

Python solution

Python
class Solution:
    def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]:
        st = mx = 0
        m = len(aliceArrows)
        for mask in range(1, 1 << m):
            cnt = s = 0
            for i, x in enumerate(aliceArrows):
                if mask >> i & 1:
                    s += i
                    cnt += x + 1
            if cnt <= numArrows and s > mx:
                mx = s
                st = mask
        ans = [0] * m
        for i, x in enumerate(aliceArrows):
            if st >> i & 1:
                ans[i] = x + 1
                numArrows -= ans[i]
        ans[0] += numArrows
        return ans

Complexity

MeasureComplexity
TimeO(2^m \times m), where m is the length of \textit{aliceArrows}
SpaceO(1) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 2212. Maximum Points in an Archery Competition is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2212. Maximum Points in an Archery Competition?
LeetCode 2212. Maximum Points in an Archery Competition is rated Medium on LeetCode.
What is the time complexity of LeetCode 2212. Maximum Points in an Archery Competition?
The Python solution on this page runs in O(2^m \times m), where m is the length of \textit{aliceArrows}.
What is the space complexity of LeetCode 2212. Maximum Points in an Archery Competition?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2212. Maximum Points in an Archery Competition cover?
LeetCode 2212. Maximum Points in an Archery Competition is tagged Bit Manipulation, Array, Backtracking and Enumeration on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview