473. Hidden Spaces Between Warehouse Cartoon Stacks
Hidden Spaces Between Warehouse Stacks

A warehouse has a row of box stacks. Every box is a cube with side length 1. Boxes are stacked from the floor upward without gaps. Each position is one unit wide, and adjacent positions touch without gaps.

You are given stackSizes, a list containing the number of boxes at each position from left to right. A value of 0 means that position is empty.

An empty unit space is hidden if there is at least one box somewhere to its left and at least one box somewhere to its right at the same height. These boxes do not need to be directly next to the space.

Consider empty unit spaces within the row, from the floor up to the top of the tallest stack. Empty spaces that are open to either end of the row do not count.

Stacks with heights 5, 1, 3, 1, and 4. Seven hidden empty spaces are highlighted between the stacks.
The highlighted spaces have boxes on both sides at the same height.

Return the total number of hidden empty unit spaces between the stacks.

Method Signature

int countHiddenSpaces(List<Integer> stackSizes)
  • stackSizes: the number of boxes at each position.
  • Returns the total number of hidden empty unit spaces between the stacks.

Constraints

  • 1 ≤ stackSizes.size() ≤ 20,000
  • 0 ≤ stackSizes[i] ≤ 100,000

Difficulty

Medium

Examples

Example 1

Input: countHiddenSpaces(stackSizes = [5, 1, 3, 1, 4])

Output: 7

Explanation: The second, third, and fourth positions contain 3, 1, and 3 hidden empty spaces, respectively. Their total is 7.

Example 2

Input: countHiddenSpaces(stackSizes = [4, 0, 2, 1, 5])

Output: 9

Explanation: The second, third, and fourth positions contain 4, 2, and 3 hidden empty spaces, respectively. Their total is 9.

Example 3

Input: countHiddenSpaces(stackSizes = [5, 1, 4, 0, 2])

Output: 5

Explanation: There are 3 hidden empty spaces above the second position and 2 above the fourth position.

Example 4

Input: countHiddenSpaces(stackSizes = [1, 2, 4, 6])

Output: 0

Explanation: Every empty space is open to the left end of the row.



Please use Laptop/Desktop or any other large screen to add/edit code.