Compute sum of minima with removals
Problem Description
You are given an array weights of n positive integers, representing product weights arranged in a line. The task is to simulate a removal process and calculate a final sum.
The process repeats until no products remain:
- Selection: Identify the product with the lightest weight among all currently remaining products.
- Tie-breaking: If there are multiple products with the same minimum weight, choose the one that currently has the smallest index in the line.
- Accumulation: Add the weight of the chosen product to a running total.
- Removal: Remove the chosen product. Additionally, remove up to its two immediate neighbors: the one on its left (if it exists) and the one on its right (if it exists). If only one neighbor exists, remove just that neighbor.
Return the final accumulated total.
Example
weights = [4, 3, 2, 1]
- Initial:
[4, 3, 2, 1]- Lightest is
1(at index 3). - Total =
1. - Remove
1. Left neighbor2exists, remove2. Right neighbor does not exist. - Remaining:
[4, 3]
- Lightest is
- Next:
[4, 3]- Lightest is
3(at current index 1). - Total =
1 + 3 = 4. - Remove
3. Left neighbor4exists, remove4. Right neighbor does not exist. - Remaining:
[]
- Lightest is
Final total = 4.
AI interview prep
Core dilemma
The central engineering conflict is efficiently managing dynamic removals of elements and their neighbors from a sequence while repeatedly finding the minimum element, balancing the O(1) removal of linked lists with the O(log N) minimum-finding of priority queues.
3 tradeoffs and 3 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Compute sum of minima with removals
Problem Description
You are given an array weights of n positive integers, representing product weights arranged in a line. The task is to simulate a removal process and calculate a final sum.
The process repeats until no products remain:
- Selection: Identify the product with the lightest weight among all currently remaining products.
- Tie-breaking: If there are multiple products with the same minimum weight, choose the one that currently has the smallest index in the line.
- Accumulation: Add the weight of the chosen product to a running total.
- Removal: Remove the chosen product. Additionally, remove up to its two immediate neighbors: the one on its left (if it exists) and the one on its right (if it exists). If only one neighbor exists, remove just that neighbor.
Return the final accumulated total.
Example
weights = [4, 3, 2, 1]
- Initial:
[4, 3, 2, 1]- Lightest is
1(at index 3). - Total =
1. - Remove
1. Left neighbor2exists, remove2. Right neighbor does not exist. - Remaining:
[4, 3]
- Lightest is
- Next:
[4, 3]- Lightest is
3(at current index 1). - Total =
1 + 3 = 4. - Remove
3. Left neighbor4exists, remove4. Right neighbor does not exist. - Remaining:
[]
- Lightest is
Final total = 4.