Ctrl K

Trim Down to One Level

Easy
There is a row of columns with heights heights[i]. A height h is called **allowed** if every column taller than h has the same height. For instance, with [10, 8, 10, 8] the height 9 is allowed (only the 10s are above it), while 5 is not. A single cut picks a height h that is allowed for the current heights and shortens every column taller than h to exactly h. Return the fewest cuts after which every column has height exactly level, or -1 if that cannot happen.
Example 1
heights=[6, 3, 6, 4], level=3 → 2

Cut everything above 4 down to 4, then everything above 3 down to 3: two cuts.

Example 2
heights=[5, 2, 7], level=4 → -1

The column of height 2 is below level 4 and nothing can be raised, so the answer is -1.

Example 3
heights=[8, 8], level=1 → 1
Constraints
  • 1 ≤ len(heights) ≤ 100
  • 1 ≤ heights[i] ≤ 100
  • 1 ≤ level ≤ 100
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPair With a Target Sum EasyThe Candidate With Most Votes EasyDoes Any Value Repeat EasyRepeat Within Reach EasyThe Lost Ticket Easy
loading Python…
Input
heights=[6, 3, 6, 4], level=3
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 123 tests on the server, hidden ones included.