Maximize weighted subsequence pairs with wildcards
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: This question evaluates combinatorial counting, string manipulation, and optimization under constraints, along with handling large-number results via modular arithmetic.
Part 1: Maximize weighted subsequence pair errors with wildcards
Constraints
- 1 <= len(s) <= 2000
- s contains only '0', '1', and '!'
- 1 <= x, y <= 10^9
Examples
Input: ("101!1", 3, 2)
Expected Output:
Input: ("!", 5, 7)
Expected Output:
Input: ("!!", 4, 7)
Expected Output:
Input: ("1!!0", 2, 5)
Expected Output:
Input: ("101!1", 3, 2)
Expected Output: 15
Input: ("!", 5, 7)
Expected Output: 0
Input: ("!!", 4, 7)
Expected Output: 7
Input: ("1!!0", 2, 5)
Expected Output: 20
Input: ("10", 3, 8)
Expected Output: 8
Input: ("!!!", 6, 2)
Expected Output: 12
Input: ("000111", 4, 9)
Expected Output: 36
Hints
- Process the string from left to right. When you place the current bit, its contribution depends only on how many 0s and 1s already exist before it.
- For a prefix, you do not need the exact assignments of previous wildcards. It is enough to know how many of them were turned into 1s and the best score for that count.
Part 2: Maximize protected population by moving security units left once
Constraints
- 1 <= n == len(population) == len(unit) <= 2 * 10^5
- 0 <= population[i] <= 10^9
- unit contains only '0' and '1'
Examples
Input: ([10, 5, 8, 9, 6], "01101")
Expected Output:
Input: ([4, 7, 2], "000")
Expected Output:
Input: ([6, 2, 9], "110")
Expected Output:
Input: ([3, 9, 4], "011")
Expected Output:
Input: ([2, 8, 1, 7], "0101")
Expected Output:
Input: ([1000000000, 0], "11")
Expected Output: 1000000000
Input: ([5], "1")
Expected Output: 5
Input: ([10, 1, 1, 10], "0110")
Expected Output: 11
Hints
- Consider each maximal consecutive block of 1s separately. Units from different blocks never need to interact.
- If a block of k consecutive units starts at position l > 1 and ends at r, those k units can protect any k cities inside the interval [l-1, r].