[LeetCode] Minimum Time to Remove All Cars Containing Illegal Goods

2167. Minimum Time to Remove All Cars Containing Illegal Goods

You are given a 0-indexed binary string s which represents a sequence of train cars. s[i] = ‘0’ denotes that the ith car does not contain illegal goods and s[i] = ‘1’ denotes that the ith car does contain illegal goods.

As the train conductor, you would like to get rid of all the cars containing illegal goods. You can do any of the following three operations any number of times:

  1. Remove a train car from the left end (i.e., remove s[0]) which takes 1 unit of time.
  2. Remove a train car from the right end (i.e., remove s[s.length - 1]) which takes 1 unit of time.
  3. Remove a train car from anywhere in the sequence which takes 2 units of time.

Return the minimum time to remove all the cars containing illegal goods.

Note that an empty sequence of cars is considered to have no cars containing illegal goods.

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int minimumTime(string s) {
int n = s.size(), left = 0, res = n;
vector<int> right(n+1);
for(int i = n-1; i >= 0; i--) {
right[i] = min(right[i] + 2 * (s[i] & 0b1111), n - i);
}
for(int i = 0; i < n; i++) {
left = min(left + 2 * (s[i] & 0b1111), i + 1);
res = min(res, left + right[i]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/09/PS/LeetCode/minimum-time-to-remove-all-cars-containing-illegal-goods/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.