KatInterview

Maximum Placement with Spacing Constraints

Greedy & IntervalsAuto-graded · 29 test cases
MediumAuto-gradedGreedy & Intervalsgreedyarraysiteration

Last updated

Tests greedy iteration with adjacency rules, requiring precise edge-case handling and index management.

You are given an integer array plots where each element is either 0 (vacant) or 1 (occupied), and an integer k representing the number of items you want to place.

Your goal is to determine whether you can place exactly k new items into the vacant plots while respecting the spacing rule: no two items may occupy adjacent positions.

An item may be placed in a vacant plot (value 0) only when both neighboring positions are also vacant or do not exist. Specifically:

  • If the plot is at the left boundary, only the right neighbor must be vacant.
  • If the plot is at the right boundary, only the left neighbor must be vacant.
  • For interior plots, both neighbors must be vacant.

Return True if it is possible to place k items under these rules, otherwise return False.

Constraints

  • 1 <= plots.length <= 2 * 10^4
  • plots[i] is either 0 or 1
  • 0 <= k <= plots.length

Examples

Example 1

Input: can_place_items([1, 0, 0, 0, 1], 1)

Output: True

Example 2

Input: can_place_items([1, 0, 0, 0, 1], 2)

Output: False

Example 3

Input: can_place_items([0, 0, 0, 0, 0], 2)

Output: True

Example 4

Input: can_place_items([1], 0)

Output: True

Hints

Hint 1

Consider a greedy strategy: place an item whenever you encounter the first valid vacant plot from left to right.

Hint 2

After placing an item at position i, update the array so that position i is marked as occupied before checking subsequent positions.

Hint 3

Handle boundary positions carefully—the leftmost and rightmost plots have only one neighbor to check.