Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: What is the minimum number of operations to make the array [5, 1, 4] strictly increasing where one operation increments any element by 1? Run the greedy code.

Problem: What is the minimum number of operations to make the array [5, 1, 4] strictly increasing where one operation increments any element by 1? Run the greedy code.
a = [5, 1, 4]
ops = 0
for i in range(1, len(a)):
    if a[i] <= a[i - 1]:
        ops += a[i - 1] + 1 - a[i]
        a[i] = a[i - 1] + 1
print(ops)
What is printed?
  1. A. 5
  2. B. 3
  3. C. 4
  4. D. 8

Correct answer: D. 8

5 stays, 1 must become 6 (5 ops), then 4 must become 7 (3 ops), total 8. Allowing equal neighbours gives 5, overwriting ops instead of adding gives 3, and summing the original drops gives 4.

More Coding Interview Problems questions

Exams that ask this topic