← Questions

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

0
AmazonCoding

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.

Reconstructed from the reported question; details may differ from what interviewers ask.

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