You are given an integer array colors where each element represents the color of an item.
Split the array into the minimum number of contiguous subarrays such that within each subarray, all elements have the same color. Return the minimum number of subarrays needed.
In other words, count the number of maximal runs of consecutive equal elements in colors.
Function Signature
def min_splits(colors: list[int]) -> int:
Rules
-
The subarrays partition the array: every element belongs to exactly one subarray, each subarray is a non-empty block of consecutive positions, and the original order is kept.
-
Equal colors separated by a different color cannot share a subarray.
Constraints
-
1 <= len(colors) <= 10^5
-
1 <= colors[i] <= 10^9
Examples
Input: colors = [1,1,2,2,3,1,1]
Output: 4
The runs are [1,1], [2,2], [3] and [1,1]. Color 1 appears in two separate runs because the 2s and the 3 sit between them.
Input: colors = [5,5,5,5,5]
Output: 1
All elements have the same color, so one subarray covers the whole array.