← Questions

Fewest decrements to make an array a 1-to-k-to-1 pyramid

0
AmazonCoding

A coding interview question asked at Amazon. It tests arrays, greedy and prefix scan.

You are given an array arr of n non-negative integers. One operation picks any index and lowers that element by exactly 1. Elements can never be raised.

Return the minimum number of operations needed to turn arr into a pyramid array:

  • it may start and/or end with any number of zeros, and
  • the remaining (non-zero) part reads 1, 2, 3, ..., k, ..., 3, 2, 1 for some peak k >= 1: it climbs by exactly 1 to a single peak, then falls by exactly 1 back to 1.

An array of all zeros counts as a pyramid (its non-zero part is empty).

Implement:

def min_ops_to_bitonic(arr: list[int]) -> int: ...

Constraints: 1 <= n <= 10^5, 0 <= arr[i] <= 10^9. Aim for better than O(n²).

Example 1

arr = [2, 5, 4, 6, 2]
output: 10

Lower it to [1, 2, 3, 2, 1]. The array sums to 19, the pyramid to 9, so 10 decrements.

Example 2

arr = [4, 4, 4, 4]
output: 12

No height-3 pyramid fits in 4 slots (it needs 5). The best is a height-2 pyramid such as [1, 2, 1, 0], sum 4, so 16 - 4 = 12.

Clarifying questions

  • Can there be zeros between the pyramid's parts? (No: the non-zero part is contiguous.)
  • Must the pyramid have a single peak, with no flat top?
  • Is an array of all zeros already done, with cost 0?
  • Can the sum overflow 32 bits? (Yes, up to about 10^14.)

What a strong answer covers

  • Sees that every element outside the pyramid goes to 0, so the cost is sum(arr) - h^2 for a pyramid of height h. The task is to find the tallest pyramid that fits.
  • Computes, in one left-to-right pass, how tall a left slope can rise to each index, capped by arr[i] and by "one more than the previous". It does the same from the right.
  • The tallest peak at an index is the smaller of the two, so the best h is the largest such value. That is O(n) time.
  • Explains why the edges of the array cap the height (a peak of h needs h - 1 cells on each side).
  • Tests both examples, all zeros, a single element, a zero in the middle, and very large values.

Follow-ups

  • Return the final array.
  • Allow increases too, each at cost 1.
  • The peak must be at a given index.
  • Allow a flat top of any width.

Where it's asked

What it tests

arrays · greedy · prefix scan

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding