Data Structures & AlgorithmsVery hardProduct company OA
Problem: A printer raises ink levels by choosing any contiguous block of cartridges and adding 1 unit to each in one operation. Starting from all zeros, find the minimum number of operations to reach the target levels.
Problem: A printer raises ink levels by choosing any contiguous block of cartridges and adding 1 unit to each in one operation. Starting from all zeros, find the minimum number of operations to reach the target levels.
def min_ops(t):
ops, prev = 0, 0
for x in t:
if x > prev: ops += x - prev
prev = x
return ops
print(min_ops([3, 1, 4, 1, 5, 9, 2, 6]), min_ops([2, 2, 2]), min_ops([1, 2, 3, 2, 1]))What is printed?- A. 18 2 3
- B. 29 6 9
- C. 9 2 5
- D. 18 3 5
Correct answer: A. 18 2 3
Look at the target from left to right: when t[i] > t[i − 1], the extra t[i] − t[i − 1] layers must START at i, while every layer that continues from i − 1 can simply be extended for free. So the answer is Σ max(0, t[i] − t[i − 1]) with t[−1] = 0: 3 + 3 + 4 + 4 + 4 = 18 for the first array, 2 for [2, 2, 2], and 3 for the hill [1, 2, 3, 2, 1]. Summing all values (29, 6, 9) treats every unit separately; O(n).
More Coding Interview Problems questions
- Problem: Count contiguous subarrays whose max − min ≤ k, using two monotonic deques and a shrinking left edge. python from collections…
- Problem: Return the k-th smallest absolute difference among all pairs of readings (n up to 10⁵, so the n² pairs cannot be listed). Binary…
- Problem: Tasks of given lengths must be packed into work sessions of at most T = 8 hours; a task cannot be split. Exact bitmask DP (state…
- Problem: Paint a 3 × n wall: each cell gets one of 3 colours and side-adjacent cells must differ. Count valid colourings by DP over row…
- Problem: Each event (start day, end day) can be attended on any ONE day in its range, and you can attend at most one event per day…
- Problem: Roads are closed one by one; after each closure report the number of connected components. Process offline: start from the graph…