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.

Example 1:

Input: s = "1100101"
Output: 5
Explanation: 
One way to remove all the cars containing illegal goods from the sequence is to
- remove a car from the left end 2 times. Time taken is 2 * 1 = 2.
- remove a car from the right end. Time taken is 1.
- remove the car containing illegal goods found in the middle. Time taken is 2.
This obtains a total time of 2 + 1 + 2 = 5. 

An alternative way is to
- remove a car from the left end 2 times. Time taken is 2 * 1 = 2.
- remove a car from the right end 3 times. Time taken is 3 * 1 = 3.
This also obtains a total time of 2 + 3 = 5.

5 is the minimum time taken to remove all the cars containing illegal goods. 
There are no other ways to remove them with less time.

思路:dp,先从左往右算,left[i] 表示到i为止,目前的最小cost是多少。

right[i] 从右往左算,right[i] 表示到i为止,从右往左,目前的最小cost是多少,然后扫描一遍,left[0....i] + right[i...n - 1]  最小;

class Solution {
    public int minimumTime(String s) {
        int n = s.length();
        int[] left = new int[n + 1];
        
        for(int i = 0; i < n; i++) {
            if(s.charAt(i) == '1') {
                left[i + 1] = Math.min(i + 1, left[i] + 2); 
            } else {
                // s.charAt(i) == '0';
                left[i + 1] = left[i];
            }
        }
        
        int res = left[n];
        
        int[] right = new int[n + 1];
        for(int i = n - 1; i >= 0; i--) {
            if(s.charAt(i) == '1') {
                right[i] = Math.min(n - i, right[i + 1] + 2);
            } else {
                // s.charAt(i) == '0';
                right[i] = right[i + 1];
            }
            // 对于每个点i,左边最小 + 右边最小,然后取最小;
            res = Math.min(res, left[i] + right[i]);
        }
        return res;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值