Fewest decrements to make an array a 1-to-k-to-1 pyramid
I was asked this
No reports yet. Sign in to say where you were asked it.
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, 1for some peakk >= 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.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
