← Questions

Maximum combination health of AI modules

0
AmazonCoding

A coding interview question asked at Amazon. It tests heap, greedy and sorting.

A lab is assembling an AI system from n candidate modules. Module i has a health health[i] (how much it contributes) and a stability stability[i] (how reliable it is). Both are non-negative integers.

You may pick a combination of at least 1 and at most k distinct modules. A combination is only as reliable as its weakest member, so its score is:

combination_health = (sum of health of chosen modules) * (minimum stability among chosen modules)

Implement:

def max_combination_health(health: list[int], stability: list[int], k: int) -> int:
    ...

Return the largest possible combination_health. Return 0 if n == 0 or k <= 0.

Constraints

  • 0 <= n <= 10^5, len(health) == len(stability)
  • 0 <= health[i], stability[i] <= 10^5
  • 0 <= k; k may exceed n

Example 1

health    = [4, 9, 2, 6]
stability = [5, 2, 8, 4]
k = 2
-> 40

Choose modules 0 and 3: (4 + 6) * min(5, 4) = 40. Module 1 has the most health, but its stability of 2 pulls any combination containing it down to at most (9 + 6) * 2 = 30.

Example 2

health    = [10, 10, 10]
stability = [1, 1, 100]
k = 3
-> 1000

Module 2 alone scores 10 * 100 = 1000, more than taking all three (30 * 1 = 30).

Aim for better than trying every subset.

Clarifying questions

  • Is it "at most k" modules, so fewer can be better?
  • Can k be larger than n?
  • Can the product overflow 64 bits? (Up to about 10^15, so no.)
  • Should we return which modules to pick?

What a strong answer covers

  • Fixes the module with the lowest stability in the combination. Then the best picks are the highest-health modules with stability at least that.
  • Sorts modules by stability, highest first, and keeps a min-heap of the best k healths seen so far with their running sum.
  • At each module, scores the current sum times its stability. That is O(n log n) time.
  • Explains why every combination is covered: its weakest module is visited, and the heap then holds the best partners.
  • Tests both examples, k = 1, k >= n, zero stabilities and n = 0.

Follow-ups

  • Exactly k modules.
  • Return the chosen modules.
  • The score uses a different aggregate, such as the sum of stabilities times the minimum health.
  • Modules must be contiguous in the input.

Where it's asked

What it tests

heap · greedy · sorting

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding