C++20 sections · 1024 units
Open in Course

Stones - Implementation

Working solution


plaintext
function countRemovals(n, colors)
count := 0
for i from 0 to n - 2
if colors[i] = colors[i + 1] then
 count := count + 1
 return count

Time is O(n)O(n), space is O(1)O(1) since you only need a counter. The nested loop tries all combinations of giving i stones to pile 1 and (n-i) to pile 2. Each combination produces a unique (weight1, weight2) pair. A set automatically handles deduplication. The final count is just the set size. This brute force enumeration works because n is small enough that O(n) pairs fit easily.