Minimum Time to Remove All Cars Containing Illegal Goods LeetCode solution in C++
1class Solution {2public:3int minimumTime(string s) {4int n = s.length();5vector<int> dp(n, 0);6if (s[n - 1] == '0') {7dp[n - 1] = 0;8} else {9dp[n - 1] = 1;10}11for (int i = n - 2; i >= 0; i--) {12if (s[i] == '0') dp[i] = dp[i + 1];13if (s[i] == '1') {14dp[i] = 2 + dp[i + 1]; // consider current index to be a middle one and remove15dp[i] = min(dp[i], n - i); // or remove all to the right16}17}18// now go from left to right19int ans = dp[0];20for (int i = 0; i < n - 1; i++) {21ans = min(ans, i + 1 + dp[i + 1]); // cost of removing all from left and dp[i+1]22}23ans = min(ans, n); // taking overall minimum24return ans;25}26};