KatInterview

Maximize Allocation Across Server Pools with Migration Limits

Dynamic ProgrammingModel answer
HardModel answerDynamic Programmingarraysdynamic-programminggreedy-intervals

Last updated

Aggregate daily resource usages and calculate optimal allocations under unrestricted and migration-bounded pool selection constraints using dynamic programming.

You are managing $N$ computing pools, indexed from $0$ to $N - 1$. Each pool $i$ has a maximum daily capacity specified in an array capacities[i]. Every morning, capacity fully restores because resources used on previous days are released.

You receive a list of consumption logs. Each log entry is represented as an object or dictionary containing three fields:

  • day: an integer representing the day index.
  • pool: an integer index ($0 \le \text{pool} < N$).
  • units: the integer amount of resources consumed by workloads on that day in that pool.

Usage on any single day for a given pool will never exceed its total capacity. Multiple log entries can share the same (day, pool) pair, in which case their consumption sums up.

Complete three tasks:

  1. Calculate Daily Available Units: For each unique day appearing in the logs, sorted in ascending order of day numbers, construct a 2D array where entry result[d][i] denotes the remaining available units in pool $i$ at the end of that day.
  2. Unbounded Pool Selection: A special job needs to be assigned to exactly one pool per day. If the job can switch pools between consecutive active days without any restriction, what is the maximum cumulative available units the job can access over all logged days?
  3. Bounded Migration Budget: Now assume the job can change its selected pool at most $K$ times across the entire sequence of logged days. A migration occurs whenever the pool chosen on day $d$ differs from the pool chosen on day $d - 1$. Determine the maximum cumulative units achievable.

Example

Input:

  • capacities = [10, 20]
  • Daily available units matrix: [[5, 7], [10, 12], [8, 18]] (3 active days)

Output:

  • Part 2 (Unbounded): max(5, 7) + max(10, 12) + max(8, 18) = 7 + 12 + 18 = 37
  • Part 3 with $K = 0$: max(5+10+8, 7+12+18) = max(23, 37) = 37
  • Part 3 with matrix [[10, 0], [0, 10], [10, 0]] and $K = 1$: Maximum available is $20$ (staying in pool 0 or pool 1 yields $20$, whereas migrating twice would yield $30$, but only $1$ switch is allowed).

Hints

Hint 1

For Part 1, group consumption entries by day and pool before subtracting from total pool capacity.

Hint 2

For Part 2, notice that each day's decision is completely independent of other days.

Hint 3

For Part 3, construct a DP state `dp[k][j]` tracking the max units collected up to the current day ending at pool `j` using at most `k` switches. Precalculate the maximum over pools for budget `k-1` to maintain an optimal state transition.