Minimum cost to remove all 1s from given Binary String as per given conditions
Given a binary sequence of 1‘s and 0‘s. Our task is to remove all 1s from the sequence in minimum cost by below operations.
- Remove an element from the left end (i.e., remove s) which costs 1 coin.
- Remove an element from the right end (i.e., remove s[s.length – 1]) which costs 1 coin.
- Remove an element from anywhere in the sequence which costs 2 coins.
Return the minimum cost to remove all the 1s from the sequence.
Input: s = “1100101”
Remove left most “1100101″ in cost of 1 coin, new s = “100101”
Remove left most “100101″ in cost of 1 coin, new s = “00101”
Remove right most “00101” in cost of 1 coin, new s = “0010”
Remove middle 1 (“0010″) in cost of 2 coin, new s = “000”.
So total 5 coins are required
Input: s = “0010”
Explanation: Remove middle 1 (“0010”) in cost of 2 coin, new s = “000”
Approach: The idea is to use DP with sliding window. Use an array dp[N] where dp[i] stores the minimum coin to remove all 1s from index i to n-1, where we can only remove from right. Follow the below steps.
- Loop from the rightmost index. So, for any index i the transition is as follows:
- If it’s a ‘0’ then dp[i]=dp[i+1]
- If it’s a ‘1’ then we have two options – either consider this element as a middle one and add 2 to dp[i+1] or remove all elements. Hence, dp[i]=min(dp[i+1]+2, n-i)
- Now, also remove elements from left. So, loop over the vector.
- When we reach any index i, we will consider that we have removed all elements from 0 to i from the leftside.
- So, our time for that index will be i+1+dp[i+1].
- Since, we have removed all elements until i, we need to just consider elements from i+1 and hence we are adding the dp[i+1] to our i+1.
- Finally return minimum answer
Below is the code implementation:
Time complexity: O(n)
Space complexity: O(n)
Please Login to comment...