Alternating Assignment

You are given n data items (n is even). Each item has an integer value called affinity. There are two destinations, RegionA and RegionB. Items must be assigned one by one in a sequence of steps. At each step, the chosen region must alternate: if RegionA is chosen at step t, then RegionB must be chosen at step t+1, and vice versa. When a region is chosen at a step, it selects one unassigned item that maximizes the total affinity for that region, unless a rule forces a specific item.

There are m rule pairs. Each rule is a pair (x, y) using 1-based indices. If item x is assigned at step t, then item y must be assigned at step t+1. If item y is assigned first, then item x must follow at the next step. Rule constraints only apply to the immediate next step. Every item must be assigned exactly once. Negative affinity values may appear.

Your task is to compute the maximum possible total affinity that RegionA can obtain over all valid assignment sequences.

Example 1:
Input: n = 6, affinity = [3, 2, -4, 8, 3, -7], m = 2, rules = [[2, 4], [3, 6]].
Items 2 and 4 form a forced pair; items 3 and 6 form a forced pair. The selection must alternate between RegionA and RegionB. The goal is to choose an assignment order that maximizes the sum assigned to RegionA.

Example 2:
Input: n = 4, affinity = [5, -2, 4, 1], m = 1, rules = [[1, 3]].
A valid sequence starting with RegionA is: RegionA picks item 1; RegionB is forced to pick item 3; remaining items are 2 and 4; RegionA picks item 4; RegionB picks item 2. RegionA’s total affinity is 5 + 1 = 6. Output: 6.

Example 3:
Input: n = 4, affinity = [-1, -5, 10, -3], m = 0.
With no rules, the regions alternate greedy selections. RegionA picks 10; RegionB picks -1; RegionA picks -3; RegionB picks -5. RegionA’s total is 7. Output: 7.



Get one-to-one training from Google Facebook engineers

Top-notch Professionals

Learn from Facebook and Google senior engineers interviewed 100+ candidates.
Most recent interview questions and system design topics gathered from aonecode alumnus.
One-to-one online classes. Get feedbacks from real interviewers.

Customized Private Class

Already a coding expert? - Advance straight to hard interview topics of your interest.
New to the ground? - Develop basic coding skills with your own designated mentor.
Days before interview? - Focus on most important problems in target company question bank.