Interview-resourceConsumption
Problem Overview
The goal is to calculate the total resource consumption of tasks selected through a specific termination process in Amazon’s Elastic Container Service (ECS).
You are given an array resourceConsumption representing n tasks. You must repeat the following steps until no tasks remain:
- Identify the Target: Find the task with the lowest resource consumption value. If multiple tasks have the same minimum value, select the one with the smallest index.
- Record the Value: Add the value of this selected task to your running total.
- Remove Tasks: Remove the selected task and its immediate neighbors (the tasks directly to its left and right) from the array.
- Update Adjacency: After removal, the remaining tasks shift to become “adjacent” to each other (the gap closes).
- Return the final sum of all selected tasks’ resource consumption values.
Example: If you have $[4, 3, 2, 1]$, you pick 1 (the minimum). Its neighbor is 2. Both are removed, leaving $[4, 3]$. Next, you pick 3 (the new minimum), and its neighbor 4 is removed. $Total = 1 + 3 = 4$.
🧠 Summary of Thoughts
ArrayList
A crucial part of this code is the Right-to-Left removal sequence:
- Right Neighbor ($i+1$)
- Current Task ($i$)
- Left Neighbor ($i-1$)
By deleting the rightmost neighbor first, the code prevents “index shifting” from affecting the positions of the remaining tasks we intend to remove in the same cycle.
The use of ArrayList.remove() is clever here because it automatically shifts subsequent elements. This naturally “closes the gap”, making tasks that were previously separated become neighbors, which perfectly matches the problem’s requirements.
Doubly Linked List & Min-Priority Queue
The goal is to reduce the time complexity from $O(n^2) \rightarrow O(n \log n)$ by decoupling the “finding the minimum” step from the “removing elements” step. We use a Min-Priority Queue for efficient selection and a Doubly Linked List to maintain task adjacency in constant time (delete element).
✅ Code(Java)
1 | |
1 | |