My friend was asked this question in an interview:
We have a vector of integers consisting only of
0s and1s. Adeleteconsists of selecting consecutive equal numbers and removing them. The remaining parts are then attached to each other. For e.g., if the vector is [0,1,1,0] then after removing [1,1] we get [0,0]. We need onedeleteto remove an element from the vector, if no consecutive elements are found.We need to write a function that returns the minimum number of
deletes to make the vector empty.
Examples 1:
Input: [0,1,1,0]
Output: 2
Explanation: [0,1,1,0] -> [0,0] -> []
Examples 2:
Input: [1,0,1,0]
Output: 3
Explanation: [1,0,1,0] -> [0,1,0] -> [0,0] -> [].
Examples 3:
Input: [1,1,1]
Output: 1
Explanation: [1,1,1] -> []
I am unsure of how to solve this question. I feel that we can use a greedy approach:
- Remove all consecutive equal elements and increment the
deletecounter for each; - Remove elements of the form
<a, b, c>wherea==canda!=b, because of we had multiple consecutivebs, it would have been deleted in step (1) above. Increment thedeletecounter once as we delete oneb. - Repeat steps (1) and (2) as long as we can.
- Increment
deletecounter once for each of the remaining elements in the vector.
But I am not sure if this would work. Could someone please confirm if this is the right approach? If not, how do we solve this?