Skip to the code
+50 XP

#528 Shape a Bar Chart Into a Peak

hard

A landing page shows a bar chart of heights. The designer wants the bars to form a single peak: strictly rising up to one bar, then strictly falling after it. The peak may not be the first or last remaining bar, and at least three bars must remain.

Write fewestRemovals(heights) that returns the fewest bars to remove (keeping the others in order) so that the remaining bars form such a peak. The input always allows at least one valid peak. A chart can have up to 100,000 bars, so comparing every bar with every earlier bar is too slow.

Example 1

Input: heights = [2,1,3,5,4,1]
Output: 1

Remove the first bar: 1, 3, 5, 4, 1 rises to 5 and then falls.

Example 2

Input: heights = [1,4,2]
Output: 0

It already rises to 4 and falls.

Constraints

  • 3 <= heights.length <= 10^5
  • 1 <= heights[i] <= 10^9
  • A valid peak can always be formed.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).