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?
  1. A. 18 2 3
  2. B. 29 6 9
  3. C. 9 2 5
  4. 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

Exams that ask this topic